编译时出现矢量push_back错误

Meg*_* Ai -2 c++ vector push-back

编译这段涉及对向量使用push_back函数的代码最终会出错.

for (int i=0; i<=n; i++)
{
    if(i==0)
    {
        Profit[i].push_back(0);
        Weight[i].push_back(0);
        Name[i].push_back("");
    }
    else
    {
        Profit[i].push_back(tosteal[i-1].getProfit());
        Weight[i].push_back(tosteal[i-1].getWeight());
        Name[i].push_back(tosteal[i-1].getName());
    }   
}
Run Code Online (Sandbox Code Playgroud)

Weight和Profit是int数据类型的声明向量,Name是字符串数据类型的向量.tosteal是一个项目对象的数组.getProfit()和getWeight()返回一个int,getName()返回一个字符串.

这些是编译器给出的错误,有些是重复:

joulethiefdynamicrefined.cpp:167:错误:请求'Profit.std :: vector <_Tp,_Alloc> :: operator []中的成员'push_back'[with _Tp = int,_Alloc = std :: allocator]((long long unsigned int)i))',它是非类型'int'joulethiefdynamicrefined.cpp:168:错误:请求'Weight.std :: vector <_Tp,_Alloc> :: operator []中的成员'push_back' with _Tp = int,_Alloc = std :: allocator]((long unsigned int)i))',这是非类型'int'joulethiefdynamicrefined.cpp:169:错误:从'const char*'转换无效'char'joulethiefdynamicrefined.cpp:169:错误:初始化'void std :: basic_string <_CharT,_Traits,_Alloc> :: push_back(_CharT)的参数1 [_CharT = char,_ Traits = std :: char_traits,_Alloc = std :: allocator]'joulethiefdynamicrefined.cpp:173:错误:请求'Profit.std :: vector <_Tp,_Alloc> :: operator []中的成员'push_back'[with _Tp = int,_Alloc = std :: allocator ](((long unsigned int)i))',它是非类型的'int'joulethiefdynamicrefined.cpp:174:错误 或:在'Weight.std :: vector <_Tp,_Alloc> :: operator []中请求成员'push_back'[与_Tp = int,_Alloc = std :: allocator](((long unsigned int)i))' ,非类型'int'joulethiefdynamicrefined.cpp:175:错误:没有匹配函数来调用'std :: basic_string,std :: allocator> :: push_back(std :: string)'/ usr/lib /gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:914:注意:候选人是:void std :: basic_string <_CharT,_Traits,_Alloc> :: push_back(_CharT)[with _CharT = char,_Traits = std :: char_traits,_Alloc = std :: allocator]

dav*_*mac 7

Profit[i].push_back(0);
Run Code Online (Sandbox Code Playgroud)

应该

Profit.push_back(0);
Run Code Online (Sandbox Code Playgroud)

等等.Profit是矢量本身; 通过说Profit[i].push_back(0),你试图将某些东西推入已经在向量中的元素之一,而不是将某些东西推入向量中.

由于元素类型int,Profit[i]是类型的int,这就是为什么你的错误:request for member ‘push_back’ in [...] which is of non-class type ‘int’.