Namespaces
Variants
Views
Actions

Talk:cpp/container/vector/insert

From cppreference.com

The iterator invalidation section is incorrect for std::vector:

Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(), all iterators and references are invalidated. Otherwise, only the iterators and references after the added element are invalidated. The past-the-end iterator is also invalidated.

The standard states that the iterator passed to the insert function is also invalidated. In particular:

Otherwise, only the iterators and references after the added element are invalidated. The past-the-end iterator is also invalidated.

should be changed to:

Otherwise, only the iterators and references *before* the insertion point remain valid.

The corner case is:

v.insert(it,value); // at this point 'it' is invalid

This is important in the sense that an iterator to the point where the new element was inserted, but obtained *before* the insertion is considered by some to refer to the 'added element', in which case the wording in the page claims that it would not be invalidated.

There is a related defect report: http://cplusplus.github.io/LWG/lwg-active.html#2256. While the DR refers to 'erase' and not insert the core issue is the same. According to the standard, the iterator is invalidated on insert/erase even if it *must* refer to a valid object.

Invalidation note updated, thank you for bringing attention to it. --Cubbi 09:21, 25 July 2013 (PDT)