简单的乘法或运算符问题

时间:2016-03-17 19:15:30

标签: c++

我正在尝试运行这个简单的代码。但我错过了一些东西。我试着看看运算符重载。有人可以解释我在这里失踪的东西。

#include <iostream>
#include <vector>
#include <cstdlib>

int main(){

    std::vector < std::vector<double> > tm;
    std::vector<int> dfg;

    // Creating a simple matrix
    double ta1[]={0.5,0.5,0};
    std::vector <double> tv1 (ta1, ta1+3);
    tm.push_back(tv1);

    double ta2[]={0.5,0,0};
    std::vector <double> tv2 (ta2, ta2+3);
    tm.push_back(tv2);

    double ta3[]={0,0.5,0};
    std::vector <double> tv3 (ta3, ta3+3);
    tm.push_back(tv3);

    double d_load =0.5;

    // doing some simple calculations 

    for (int destinationID = 1; destinationID <= tm.size(); destinationID++){
         float randomNum = ((double) rand())/((double) RAND_MAX);
         if (randomNum <= d_load * tm[destinationID - 1])
             dfg.push_back(destinationID);
    }

    return 0;
}

我收到以下错误。

error: no match for ‘operator*’ in ‘d_load * tm.std::vector<_Tp, _Alloc>::operator[] [with _Tp = std::vector<double>, _Alloc = std::allocator<std::vector<double> >, std::vector<_Tp, _Alloc>::reference = std::vector<double>&, std::vector<_Tp, _Alloc>::size_type = long unsigned int](((long unsigned int)(destinationID + -0x00000000000000001)))’

2 个答案:

答案 0 :(得分:1)

以下行无效:

d_load * tm[destinationID - 1]

由于tmstd::vector<std::vector<double>>tm的元素是std::vector<double>,而不是double。如果您想要将每个数字相乘或检查每个数字是否与条件匹配,则必须迭代您从tm[]获得的元素

答案 1 :(得分:1)

tmstd::vector<std::vector<double>>,因此它实际上是{strong> 2 维动态数组double。这意味着要访问double中的各个tm元素,您可以使用以下内容:

double value = tm[destinationID - 1][theValueIndex];

这是您错过的循环的[theValueIndex]部分。

由于我们不知道您想要如何穿越阵列的确切意图,我会留给您填写这个空白。

相关问题