首页 文章

编译时出现矢量push_back错误

提问于
浏览
-2

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

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'[with _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]

1 回答

  • 7
    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’ .

相关问题