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