0

Imagine I had this map:

std::map<int, int> map;

map.insert(std::pair<int, int>(1, 1));
map.insert(std::pair<int, int>(2, 2));
map.insert(std::pair<int, int>(3, 3));
map.insert(std::pair<int, int>(4, 4));
map.insert(std::pair<int, int>(5, 5));

What would be the best to use?

This:

for(std::pair<int, int> pair : map) {} //or
for each(std::pair<int, int> pair in map) {}

Or this:

for(std::map<int, int>::iterator itr = map.begin(); itr != map.end(); itr++) {} //or
for(auto itr = map.begin(); itr != map.end(); itr++) {}
jay
  • 29
  • 5

2 Answers2

2

The best to use is:

for (auto&& entry : map)
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • The first creates unnecessary copies. The second can sometimes fail (not for maps, but in general). See http://stackoverflow.com/questions/13130708/what-is-the-advantage-of-using-universal-references-in-range-based-for-loops – Christian Hackl Sep 22 '15 at 18:55
1

From a performance perspective they are equivalent. The first two are generally preferred because they are much more readable.

alexgolec
  • 26,898
  • 33
  • 107
  • 159
  • Ah thanks. this is essentially what I wanted to know; I wondered if they had different performance, as I see iterators mentioned everywhere and the method I described above mentioned nowhere. Will accept answer when possible :) – jay Sep 22 '15 at 18:28
  • @jay But you should still use `auto` (see my answer)! – C. K. Young Sep 22 '15 at 18:33
  • @ChrisJester-Young Yeah, that's a valid point. I'm accepting this one due to the extra info, but thanks for the info you gave me :) – jay Sep 22 '15 at 18:34
  • [for each in](https://msdn.microsoft.com/en-us/library/ms177202.aspx) is a non standard Microsoft extension that IMHO is not preferable as it is not portable. – NathanOliver Sep 22 '15 at 18:36
  • @NathanOliver Yeah I know, I added that there just simply to explain a little bit better. I prefer `for(X : Y)` anyways :) – jay Sep 22 '15 at 18:37
  • @NathanOliver C++/CLI is actually an ECMA standard so it's not correct to call it nonstandard, but of course it's not standard C++. ;-) – C. K. Young Sep 22 '15 at 18:43