scenario's under which Container invalidate its iterator

P

Pallav singh

Q what are different scenario's under which a Container can ,
invalidate its iterator ?
 
P

Pallav singh

Different containers do it in different situations.  One common for all
of them is when the element to which the iterator refers is erased.

std::list does not invalidate any other iterators when you erase the
element.  std::vector can invalidate all iterators if it reallocates
memory (when it's growing).  std::vector also invalidates all iterators
to elements following the erased one...  What book on the Standard
library are you reading that doesn't explain all that?

V

1. Uninitialized iterators:
vector<int>::iterator it;
it++;

2. Out of range access:
vector<int>::iterator it = vec.end();
it++;

3. Comparing iterators from different ranges or containers:
for (it = vec1.begin(); it != vec2.end(); ++it)

4. use of invalidated or "dangling" iterators:
vector<int> it = vec.begin();
vec.clear();
it++;
 
P

Pallav singh

Undefined Behavior


Undefined Behavior


Implementation-defined Behavior


Undefined Behavior

None of those have anything to do with invalidating iterators.

Invalidation of iterators
Invalidation of iterators into vectors:
1. insertion in a vector invalidates iterators from the point of
insertion to the end of the vector.
2. if insertion causes reallocation to provide more memory then
all iterators become invalid.
3. erase invalidates all iterators at and past the point of
erasure.
4. a safe strategy is to assume that any iterator into a vector
becomes invalid after either insertion or erasure.

Invalidation of iterators into deques:
insertion and erasure in the interior invalidates all iterators.

Invalidation of iterators into lists:
list insertions never invalidate iterators and erase invalidates
only iterators pointing to the erased items.

Use of invalid iterators:
The only safe things you can do with an invalid iterator is to
reinitialize it by assigning a new iterator value to it or destroy it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,479
Members
44,900
Latest member
Nell636132

Latest Threads

Top