-1

I have a simple question: what will happen if I keep incrementing an iterator when it reaches the end() (one past the last) of a C++ STL container? e.g.

set<int> intSet;
intSet.insert(0);
intSet.insert(1);
intSet.insert(2);
set<int>::iterator setIter = intSet.begin();
for (int i = 0; i < 10; i++)
  setIter++;

so, will setIter always be intSet.end()? or this is an undefined behavior (can give me inconsistent junk)?

user3277360
  • 127
  • 4

2 Answers2

1

It will throw a runtime error in VS2013. However, it will not in G++ (ideone). However it is undefined behavior if you ever use it. It is definitely not equal to intSet.end()

yizzlez
  • 8,757
  • 4
  • 29
  • 44
0

The mere act of incrementing it will do nothing, at least in the GNU compilers.

If you try to dereference it, that invokes undefined behavior.

See this question for more discussion.

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • Thx, yes, I know I should not dereference it. I just need to know if this can give me consistent behavior. Seems like it won't if I use different compilers. – user3277360 Apr 24 '14 at 02:05