8

For associative containers, can the ++ operator send an iterator past the end of a collection?

Example:

map<UINT32, UINT32> new_map;
new_map[0] = 0;
new_map[1] = 1;

map<UINT32, UINT32> new_iter = new_map.begin();

++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;
++new_iter;

At the end of this, does new_iter == new_map.end(), or does it end up in the great unknown?

Note: I know this is messed up and not the way to do things. I'm working around some WTF corporate code.

Mike Lewis
  • 734
  • 1
  • 7
  • 18
  • 1
    So have you compiled it and checked whether it will be new_map.end() at the end? Probably the easiest way to answer a question such as this if you aren't sure. – Goz Aug 24 '09 at 21:09
  • 9
    @Goz: No, that would just answer what one implementation is doing. – sbi Aug 24 '09 at 21:11
  • 3
    Possible duplicate of [What happens if you increment an iterator that is equal to the end iterator of an STL container](https://stackoverflow.com/questions/1057724/what-happens-if-you-increment-an-iterator-that-is-equal-to-the-end-iterator-of-a) – Raedwald Nov 29 '17 at 10:56

3 Answers3

29

If you increment the end iterator, the result is undefined behavior. So, it could remain end, or go off the end, or email your grandmother a link to goatse.

See also: What if I increment an iterator by 2 when it points onto the last element of a vector?

Community
  • 1
  • 1
Tyler McHenry
  • 74,820
  • 18
  • 121
  • 166
11

The precondition on the ++ operator for a forward iterator is that the iterator is dereferenceable. This implies it cannot be past the end of the map, so your code gives undefined behaviour. This is described in section 24.1.3 of the C++ Standard.

5

As others have pointed out, incrementing the end iterator causes undefined behaviour, however it's worth noting that Visual Studio 2008 will throw a debug assertion at runtime (due to its checked iterators) if you do this.

Alan
  • 13,510
  • 9
  • 44
  • 50