Use of for_each on map elements
You can iterate through a std::map
object. Each iterator will point to a std::pair<const T,S>
where T
and S
are the same types you specified on your map
.
Here this would be:
for (std::map<int, MyClass>::iterator it = Map.begin(); it != Map.end(); ++it)
{
it->second.Method();
}
If you still want to use std::for_each
, pass a function that takes a std::pair<const int, MyClass>&
as an argument instead.
Example:
void CallMyMethod(std::pair<const int, MyClass>& pair) // could be a class static method as well
{
pair.second.Method();
}
And pass it to std::for_each
:
std::for_each(Map.begin(), Map.end(), CallMyMethod);
C++11 allows you to do:
for (const auto& kv : myMap) {
std::cout << kv.first << " has value " << kv.second << std::endl;
}
C++17 allows you to do:
for (const auto& [key, value] : myMap) {
std::cout << key << " has value " << value << std::endl;
}
using structured binding.
UPDATE:
const auto is safer if you don't want to modify the map.