I have a code just like this:
std::vector<int> v1 = { 1, 2, 3, 4 };
std::vector<int> v2 = { 7, 8, 9, 10 };
std::vector<int>::iterator it = std::next(v1.begin());
v1 = v2;
int test = *it;
std::cout << test;
The above code will throw an error: iterator not dereferencable.
However, if I replace vector with list as follows:
std::list<int> v1 = { 1, 2, 3, 4 };
std::list<int> v2 = { 7, 8, 9, 10 };
std::list<int>::iterator it = std::next(v1.begin());
v1 = v2;
int test = *it;
std::cout << test;
The code just ran as expected without error.
From Iterator invalidation rules, and the std::list::operator=, I was told that after the call to operator =, all iterators, references and pointers related to this container are invalidated, except the end iterators. But why the above code with std::list works? Did I misunderstand something essential?