Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL Vector, Iterator and Insert (C++)

I have a method to which a vector's iterator is passed. In this method I'd like to add some elements into the vector, but I am not sure whether this is possible when having only the iterator

void GUIComponentText::AddAttributes(vector<GUIComponentAttribute*>::iterator begin, vector<GUIComponentAttribute*>::iterator end)
{
    for (vector<GUIComponentAttribute*>::iterator i = begin; i != end; ++i)
    {
        GUIComponentAttribute &attrib = *(*i);

        // Here are the GUIComponentAttribute objects analyzed - if an object of a 
        // special kind appears, I would like to add some elements to the vector
    }
}

Thanks Markus

like image 891
Markus Erlacher Avatar asked Jan 19 '23 05:01

Markus Erlacher


2 Answers

In the code you show, this is not possible. Especially because you should not add/remove elements to/from a vector while you iterate over it.

like image 175
Björn Pollex Avatar answered Jan 25 '23 12:01

Björn Pollex


This is a long standing design "issue" in the STL. Iterators do not allow the modification of the structure of the underlying sequence they are iterating over: ie you can modify (sometimes) the elements themselves, but you cannot add/remove elements. Though InputIterator and OutputIterator are a bit special in this regard... hum...

This is actually the cause of the erase/remove idiom:

vec.erase(std::remove_if(vec.begin(), vec.end(), predicate), vec.end());

So, no, sorry, there is no way to actually modify the vector.

However, as exposed above, you can perfectly use the remove_if algorithm and simply return the new end of the valid range... or you can ask for the whole vector to begin with.

As noted by Björn, modifying a sequence structure while iterating over it is error-prone.

like image 26
Matthieu M. Avatar answered Jan 25 '23 12:01

Matthieu M.