Using set::begin() iterator after insertion

c++, containers, iterator, set

Solution

When you call `s.begin()` here, it returns an end iterator because the container is empty. This iterator is not invalidated by the insertions: after each insertion, this iterator is still an end iterator.

Dereferencing this iterator causes your program to exhibit undefined behavior (end iterators cannot be dereferenced).

Problem

Consider the following code: ``` std::set<int> s; auto it = s.begin(); s.insert(1); s.insert(2); std::cout << *it << std::endl; ``` The output (at least for me) is `2`. What's happening here? What's the state of `it` when I dereference it? I know that when I call `begin()` on an empty set, I get an iterator equivalent to `end()`. I also know that calling `insert` on a `set` doesn't invalidate its iterators. Does the iterator somehow stay equivalent to `end()` even though I've now inserted elements into the `set` and so now I'm getting undefined behaviour? Is that defined by the standard?

Original source

Related problems