On Aug 19, 3:22*am, "subramanian10...@yahoo.com, India"
<subramanian10...@yahoo.com> wrote:
> 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
|