문제

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)?

도움이 되었습니까?

해결책 2

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.

다른 팁

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()

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top