Why is the std :: vector iterator invalid after calling erase ()?

The C ++ reference clearly indicates that a call std::vector::erase(it)on an iterator will invalidate all iterators pointing to and after the element to be erased. http://en.cppreference.com/w/cpp/container/vector/erase

I understand why such iterators became uninteresting after the call erase, but I am curious why they should become invalid, what implementation details require this?

For example, the standard states what std::vectorshould be implemented with stored elements, and elements can be accessed not only through iterators, but also using offsets on regular pointers to elementstherefore it seems logical that iterators for such a container are likely to be implemented as pointers - but then how can pointers become invalid?

+4
source share
3 answers

One of the principles on which the iterator’s conceptual idea is based is as follows: as long as the iterator remains smooth, dereferenced and unmodified, it must refer to the same object. In other words, dereferencing the same iterator several times should give the same value. Algorithms using iterators can rely on this.

What you propose will lead to an iterator that will “magically” change the value it refers to, although the iterator itself remains unchanged. This is unacceptable in the conceptual idea of ​​an iterator.


, , , , (, std::random_shuffle). , , . , erase? .

+6

"invalidated" , " , ", " - "

( ):

vector<int> v = {0, 1, 2, 3, 4, 5};
vector<int>::iterator iter = v.begin() + 3;  // "points to" 3
assert(*iter == 3);
v.erase(v.begin());

iter . , .

+2

std::vector

That's why. If you erase an element inside a vector, the elements must at least be shifted. You might not protect debugs:

std::vector< int > test= {1,2,3,4,5,6,7};
auto it= test.begin( ) + 2;
test.erase( it );
std::cout << *it << std::endl;

And he will most likely print "4". But there is no guarantee. What if the vector is re-illustrated? What if you remove test.begin( ) + 6? If you resize the vector, you can move it.

More details

+1
source

Source: https://habr.com/ru/post/1662468/


All Articles