Search code examples
c++vectoriteratorpush-back

push_back in a vector in a object


I have a profesor class with this atribute

vector<int> hDisponibles;

If I have a vector of this class

set<profesor> profesores;

I try this

set<profesor>::iterator itP;
itP = profesores.begin();    
while ( itP != profesores.end() ){                
    (*itP).hDisponibles->push_back(0);                                                    
    itP++;
}

but this errors

utils.cpp:138: error: passing ‘const std::vector<int, std::allocator<int> >’ as ‘this’     argument of ‘void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = int, _Alloc = std::allocator<int>]’ discards qualifiers

Solution

  • Your problem is that the vector you are trying to call push_back on is const. This is because (since C++11) the elements of a std::set are accessed through const_iterators, since changing them might change how they compare and therefore corrupt the set. To solve that you have two options:

    1. If hDisponibles has no effect on how profesor compare and it doesn't do to much damage to your overall structure you can declare it mutable like this: mutable vector<int> hDisponibles;. mutable members can be changed even if the structure they reside in is const
    2. I that is not an option, you have to remove the profesor from the set (into a temporary), do your push_back and reinsert it (be careful about iterator invalidation). Of course this is quite costly.

    Your code as posted has an additional bug, since hdisponsibles is an object, but push_back is called as if it was a pointer. From your compilermessage it doesn't seem like that bug is in your actual code, but just in case it should be:

    (*itP).hDisponibles.push_back(0);    
    

    Edit: Found the section in the standard draft (the value type is the same as the key for set and multiset: N3290 §23.2.4/6

    iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type. [Note: iterator and const_iterator have identical semantics in this case, and iterator is convertible to const_iterator. Users can avoid violating the One Definition Rule by always using const_iterator in their function parameter lists. —endnote ]