简体   繁体   中英

Vector push_back error when compiling

Compiling this segment of code involving using the push_back function for vectors ends up in an error.

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 and Profit are declared vectors of the int data type and Name is a vector of the string data type. tosteal is an array of items objects. getProfit() and getWeight() return an int and getName() returns a string.

These are the errors the compiler gives, some are repeats:

167: error: request for member ‘push_back’ in ‘Profit.std::vector<_Tp, _Alloc>::operator[] [with _Tp = int, _Alloc = std::allocator<int>](((long unsigned int)i))’, which is of non-class type ‘int’

168: error: request for member ‘push_back’ in ‘Weight.std::vector<_Tp, _Alloc>::operator[] [with _Tp = int, _Alloc = std::allocator<int>](((long unsigned int)i))’, which is of non-class type ‘int’

169: error: invalid conversion from ‘const char*’ to ‘char’

169: error:   initializing argument 1 of ‘void std::basic_string<_CharT, _Traits, _Alloc>::push_back(_CharT) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]’

173: error: request for member ‘push_back’ in ‘Profit.std::vector<_Tp, _Alloc>::operator[] [with _Tp = int, _Alloc = std::allocator<int>](((long unsigned int)i))’, which is of non-class type ‘int’

174: error: request for member ‘push_back’ in ‘Weight.std::vector<_Tp, _Alloc>::operator[] [with _Tp = int, _Alloc = std::allocator<int>](((long unsigned int)i))’, which is of non-class type ‘int’

175: error: no matching function for call to ‘std::basic_string<char, std::char_traits<char>, std::allocator<char> >::push_back(std::string)’
 note: candidates are: void std::basic_string<_CharT, _Traits, _Alloc>::push_back(_CharT) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]
Profit[i].push_back(0);

Should be

Profit.push_back(0);

And so on. Profit is the vector itself; by saying Profit[i].push_back(0) , you are trying to push something into one of the elements that is already in the vector, rather than pushing something into the vector.

Since the element type is int , Profit[i] is of type int , which is why you get the error: request for member 'push_back' in [...] which is of non-class type 'int' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM