Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

++it or it++ when iterating over a map?

Examples showing how to iterate over a std::map are often like that:

MapType::const_iterator end = data.end(); 
for (MapType::const_iterator it = data.begin(); it != end; ++it)

i.e. it uses ++it instead of it++. Is there any reason why? Could there be any problem if I use it++ instead?

like image 329
laurent Avatar asked Aug 03 '11 13:08

laurent


1 Answers

it++ returns a copy of the previous iterator. Since this iterator is not used, this is wasteful. ++it returns a reference to the incremented iterator, avoiding the copy.

Please see Question 13.15 for a fuller explanation.

like image 65
Dark Falcon Avatar answered Sep 20 '22 12:09

Dark Falcon