How can I modify values in a map using range based for loop?

Plain auto is by value (you get a copy). Use auto&.


Note that since C++17, you can use structured bindngs:

for (auto & [key, value] : foobar)
  std::cout << "{" << key << ", " << ++value << "} ";

I like this mechanism since key and value is much more readable for maps than something as p.first and p.second.


You can turn auto into auto& if you want to mutate/modify the container, for instance:

#include <map>
#include <iostream>

int main()
{
  std::map<int, int> foobar({{1,1}, {2,2}, {3,3}});
  for(auto& p : foobar) {
    ++p.second;
    std::cout << '{' << p.first << ", " << p.second << "} ";
  }
  std::cout << std::endl;
}

compiles ands outputs

{1, 2} {2, 3} {3, 4} 

live example


Using the auto keyword sends a copy of each value into the loop. If you want to mutate the original value in the map you need to use auto&.