2016-11-08 147 views
-2

编译涉及使用向量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()); 
    } 
} 

重量和利润被声明int数据类型的载体和名称是字符串数据类型的载体。 tosteal是项目对象的数组。 getProfit()和getWeight()返回一个int,getName()返回一个字符串。

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

joulethiefdynamicrefined.cpp:167:错误:请求部件“Profit.std '的push_back' ::矢量< _TP,_Alloc> ::操作者[] [with _Tp = int,_Alloc = std :: allocator](((long unsigned int)i))',它是非类类型'int' joulethiefdynamicrefined.cpp:168:error:request for member' ('(long unsigned int)i))'中的'push_back',其中'weight_std :: vector'中的'push_back'类型'int' joulethiefdynamicrefined.cpp:169:错误:从'const char *'无效转换为'char' joulethiefdynamicrefined.cpp:169:错误:初始化参数1'void std :: basic_string < _CharT,_Traits,_Alloc> :: push_back(_CharT)[with _CharT = char,_Traits = std :: char_traits,_Alloc = std ::分配器]' joulethiefdynamicrefined.cpp:173:错误:在'Profit.std :: vector < _Tp,_Alloc> :: operator [] [with _Tp = int,_Alloc = std :: allocator]中的成员'push_back'的请求( ((long unsigned int)i))',它是非类类型'int' joulethiefdynamicrefined.cpp:174:错误:请求成员'push_back'在'Weight.std :: vector < _Tp,_Alloc>中: :运算符[] [使用_Tp = int,_Alloc = std :: allocator](((long unsigned int)i))',它是非类类型'int' joulethiefdynamicrefined.cpp:175:错误:不匹配函数调用'std :: basic_string,std :: allocator> :: push_back(std :: st环)' /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/basic_string.h:914:note :候选是:空隙的std :: basic_string的< _CharT,_Traits,_Alloc> ::的push_back(_CharT)[与_CharT =炭,_Traits =标准:: char_traits,_Alloc =标准::分配器]

+1

不是你要求的,但'for(int i = 0; i <= n; i ++)'中的'i'的范围并不合适。 –

+0

_Weight和Profit是int数据类型_...的已声明向量,那么为什么您需要执行'Weight [i] .push_back'? – smac89

回答

5
Profit[i].push_back(0); 

如若是

Profit.push_back(0); 

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

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