1

I know that in order to loop through a map in C++11 I can use the following code:

std::mymap<std::string, myclass>

for(auto item : mymap)
{
    // code here
}

What exactly is referred to by item? Is it the map key? The value that is currently accessed? If I want to do something with the value, how do I access it?

intcreator
  • 4,206
  • 4
  • 21
  • 39

1 Answers1

2

Iter refers to a std::pair<std::string, myclass> in your context. So iter.first is your key and iter.second is value for your example.

If you want to modify value inside loop block, you can write as follows:

iter.second=<new value>

If you don't need to modify the value better to use your range loop as follows:

for(const auto& iter : mymap)
{
 //
}
Steephen
  • 14,645
  • 7
  • 40
  • 47
  • Okay, I think this makes sense. If I have a member function, I would just use `iter.second.myfunction();`, correct? – intcreator Jul 26 '15 at 02:23
  • 2
    In your example context, if you have a function like `myclass::myfunction()`, you can call as `iter.second.myfunction()` – Steephen Jul 26 '15 at 02:25
  • 1
    It's a `std::pair` actually. – Lightness Races in Orbit Jul 26 '15 at 02:28
  • What are the advantages of using `const`? How is `&iter` different from `iter`? Will I need to access `iter.first` and `iter.second` differently in the case of `&iter`? – intcreator Jul 26 '15 at 02:29
  • 1
    @brandaemon if you are not making any changes in iterated elements, if you use `const` code will be more clear with your intention. If you use reference instead value semantics, system don't need to create temporaries by copying the original elements. – Steephen Jul 26 '15 at 02:35
  • `iter` (which is a pretty bad name, since it isn't an iterator) is a `std::pair`. Note the `const`. – T.C. Jul 26 '15 at 02:50
  • @T.C. If it's not an iterator, what exactly is it? – intcreator Jul 26 '15 at 02:58