Pergunta

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

Foi útil?

Solução 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.

Outras dicas

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top