title: How can I modify values in a map using range based for loop?
body: <p>I have a range based for loop to iterate over elements in <code>foobar</code> as follows:</p>
  
  <pre><code>#include &lt;map&gt;
  #include &lt;iostream&gt;
  
  int main()
  {
    std::map&lt;int, int&gt; foobar({{1,1}, {2,2}, {3,3}});
  
    for(auto p : foobar) 
    {
      ++p.second;
      std::cout &lt;&lt; "{" &lt;&lt; p.first &lt;&lt; ", " &lt;&lt; p.second &lt;&lt; "} ";
    }
    std::cout &lt;&lt; std::endl;
  
    for(auto q : foobar) 
    {
      std::cout &lt;&lt; "{" &lt;&lt; q.first &lt;&lt; ", " &lt;&lt; q.second &lt;&lt; "} ";
    } 
    std::cout &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>This code produces the following output:</p>
  
  <pre><code>{1, 2} {2, 3} {3, 4}
  {1, 1} {2, 2} {3, 3}
  </code></pre>
  
  <p>The first line is modified and printed inside a for loop and the second line supposedly prints the same modified values.  Why don't the outputs match?  Are changes to <code>std::map</code> only effective in the scope of the loop?  Is there a way I can not only access but modify these values?</p>
  
  <p>A <a href="http://cpp.sh/6rxx" rel="noreferrer">running version of this code</a> can be found on cpp.sh.</p>
  
  <p><strong>EDIT:</strong> The example given here was modified to match the accepted answer for clarity.</p>