Plz explain this pitfall

Seriously,this is from my book :

ITERATORS AND REMOVING ELEMENTS
Adding or removing an element to or from a container can affect other iterators. In general, there
is no guarantee that the iterators will be located at the same element after an addition or deletion.
Some containers do, however, guarantee that the iterators will not be moved by additions or
deletions, except of course if the iterator is located at an element that is removed.
Of the template classes we have seen so far, list and slist guarantee that their iterators will
not be moved by additions or deletions, except of course if the iterator is located at an element
that is removed. The template classes vector and deque make no such guarantee.


I couldn't understand,plz explain,thanks in advance.
An iterator is used to reference a particular element in a container.

For example, iterator 'myIt' may reference the 3rd element in a vector container.

If you change the content of the vector, for example by appending or deleting an element, 'myIt' is no longer guaranteed to still be referencing the 3rd element.

If you repeat the example with a list container, 'myIt' does still reference the 3rd element.

The bits about deleting say that if you delete the 3rd element, the iterator no longer references the 3rd element!

Cheers,
Jim
Thank you,

How can list and slist guarrantee such thing not to happen ?
It's because of the way they're implemented internally.

Vectors guarantee that their content is in a contiguous block of memory, so you can access the elements like a normal array. But for this to happen, adding an element, for example, may require the vector be moved to a new location in memory if the currently allocated space has been used up. After doing this, any iterators won't point to the same bit of memory.

Lists, on the other hand, can be implemented as a linked list, so their elements can be scattered all over available memory in no particular order, so no existing elements have to be affected when adding new ones.

Jim
Thank you !
Topic archived. No new replies allowed.