1

I was wondering why the test below

end_iter_mem == intList.end()

return true

coliru

Shouldn't the end() "value" of the container evolves when (among other) container's number of elements increases ?

#include <iostream>
#include <list>

using namespace std;

int main()
{
    list<int> intList = {1,2,3};

    auto end_iter_mem = intList.end();

    intList.push_back(4);

    cout << (end_iter_mem == intList.end()) << endl;

    return 0;
}
NGI
  • 852
  • 1
  • 12
  • 31

1 Answers1

1

Iterators for lists are not invalidated after list::push_back operations, from cppreference

No iterators or references are invalidated.

But this does not mean that this is true for all containers. For example for vectors the documentation says

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.


tl;dr You have to consult the documentation to find out whether iterators are invalidated and which iterators are invalidated after a container modification.

Curious
  • 20,870
  • 8
  • 61
  • 146