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
First, you’ll have to change the interface. Given two iterators,
there’s no way to get back to the container to which they refer; so if
you want to modify the container, you’ll have to pass a reference to it,
i.e.:
Having done that: insertion can invalidate iterators. So it depends on
where you want to insert. If you want to insert at the current
position:
std::vector<>::insertof a single element returns aniterator to that element, which was inserted before your element, so you
can assign it to your iterator, adjust (if necessary), and continue:
If you’re appending (
push_back), the problem is a bit more complex;you need to calculate the offset, then reconstruct the iterator:
In this case, it is probably simpler to iterate using a
size_tand[], rather than an iterator.