question on invalidation of iterators on vector<T>

S

subramanian100in

Suppose I have

vector<int> c;
for (int i = 0; i < 10; ++i)
c.push_back(i);

vector<int>::iterator it = find(c.begin(), c.end(), 5);

If I do,
c.insert(c.begin(), 10);

then it can cause increase in container size in which case
reallocation happens and so the insertion operation can POTENTIALLY
invalidate all iterators into the vector.

How to know whether all the iterators into a vector are invalidated
after insertion ? Or should we safely always assume that all iterators
into a vector will become invalid after insertion ?

Now consider
c.erase(it--);

Can reallocation happen due to the shrinkage of vector size by means
of erasure ? If this is true, then erase also can invalidate all
iterators into a vector. Am I correct ?

Also, is it correct to say 'it--' in the argument passed (ie postfix
decrement on the iterator argument passed) to erase function as done
above ? Will it be a valid iterator after erase ?

Or equivalently, should I say,

vector<int>::iterator nit = c.erase(it);
--nit;

Kindly clarify

Thanks
V.Subramanian
 
J

joseph cook

Suppose I have
How to know whether all the iterators into a vector are invalidated
after insertion ? Or should we safely always assume that all iterators
into a vector will become invalid after insertion ?

This is generally a good idea to assume such, but if vector.size()
does not exceed the vector.capacity() before you did the insert, then
the iterator will still be valid. (You can ensure the capacity() is
at least a certain size, by calling vector.reserve(size) up front
somewhee.
Now consider
c.erase(it--);

Can reallocation happen due to the shrinkage of vector size by means
of erasure ? If this is true, then erase also can invalidate all
iterators into a vector. Am I correct ?

No, erase will only invalidate all iterators after 'it'.
Also, is it correct to say 'it--' in the argument passed (ie postfix
decrement on the iterator argument passed) to erase function as done
above ? Will it be a valid iterator after erase ?

Assuming "it" didn't point to begin()
Or equivalently, should I say,

vector<int>::iterator nit = c.erase(it);
--nit;

Yes, this is better, although be sure "it" doesn't point to begin here
too. Why do you want to point to the element just before the one that
was deleted? Generally, you just want "nit = c.erase(it)" to get you
to the next element. Id you are trying to walk through a vector in
reverse order, consider a reverse_iterator

Joe Cook
 

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,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top