There’s a lot of messed-up info here.
An iterator is a thinly-veiled pointer. That is why it looks like a pointer and acts like a pointer.
Every container class implements an iterator in the simplest way possible. For example:
• For a vector, an iterator can’t get any simpler: just be a pointer.
• For a deque, it gets more complicated because the iterator class must know how to jump from block to block.
• For a list, the iterator just has to know how to get from one node to the next, and to dereference as the node’s data object.
All this means is that there have to be strict considerations about when an iterator becomes invalid.
• For a vector,
any modification to the vector invalidates
all iterators into the vector. This is because a vector resize may
move the data() to another spot in memory.
• For a deque, we can limit the potential damage to only invalidating iterators after the modification point.
• For a list, we can have the nice property that no iterators are invalidated.
Always, always, refer to the documentation.
Repeater only quoted part of the documentation. The full text is:
vector::insert says:Iterator validity
If a reallocation happens, all iterators, pointers and references related to the container are invalidated.
Otherwise, only those pointing to position and beyond are invalidated, with all iterators, pointers and references to elements before position guaranteed to keep referring to the same elements they were referring to before the call. |
Emphasis added
In practice, this means you either need to test for reallocation, or simply assume that any iterators you have are all invalid.
If you are only looking to
replace an element, you can do that without invalidating iterators:
1 2 3
|
for (auto iter = v.begin(); iter != v.end(); ++iter)
if (*iter = element_to_replace)
*iter = new_element_value;
|
If you are looking to
insert elements, that takes a little more work. An unoptimized loop might look like this:
1 2 3
|
auto iter = v.begin();
while ((iter = std::find( v.begin(), v.end(), some_element )) != v.end())
v.insert( iter, new_element );
|
Hope this helps.
[edit] friggin bbcode