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

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

Leave a Comment