0

Say I have a simple program as so:

int main(void) { std::list<int> l; auto it = l.begin(); auto it2 = l.insert(l.begin(), 5); std::cout << (it == it2) << std::endl; } 

Doesn't this show that the iterator it has been invalidated by inserting into the list. Yet the C++ standard says that insertion into a list does not invalidate iterators.

Originally it would probably hold a nullptr since the list was empty. Now it no longer points to any iterator part of the list. So is it not invalidated?

5
  • 4
    auto it = l.begin(); returns std::list::end() as the container is currently empty. You can never have a item inserted at this position; so the test will always fail. it remains a valid iterator. Commented Jul 23, 2018 at 18:18
  • 2
    Basically if you print (it == l.end()) instead, the program outputs 1. Commented Jul 23, 2018 at 18:21
  • 2
    As @RichardCritten pointed out it == l.end(), while it2 will point to the inserted item. So the result you're getting is what would be expected. No iterators are invalidated here. "Doesn't this show that the iterator it has been invalidated by inserting into the list." No, it does not show that. Commented Jul 23, 2018 at 18:22
  • 1
    @Arcinde: You are correct, and notably it's the same before and after the insert. Commented Jul 23, 2018 at 18:25
  • Re: "Originally it would probably hold a nullptr since the list was empty." Probably not. But it doesn't matter, so long as the requirements for iterators are satisfied. Commented Jul 23, 2018 at 19:12

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.