-2

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>]
PR06GR4MM3R
  • 397
  • 2
  • 13
Megumi Ai
  • 89
  • 2
  • 9
  • 1
    Not what you ask, but the range of `i` in `for (int i=0; i<=n; i++)` does not feel right. –  Nov 08 '16 at 01:30
  • _Weight and Profit are declared vectors of the int data type_...ok so why do you need to do `Weight[i].push_back`? – smac89 Nov 08 '16 at 01:31

1 Answers1

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

davmac
  • 20,150
  • 1
  • 40
  • 68