title: Find max values in a map from key pair first
body: <p>this is the first time for me to post something, so apologies if the formatting isn't correct or the question is framed incorrectly - I will take any feedback on those elements so I can improve.</p>
  <p>I have a map created:</p>
  <p>std::map&lt;std::pair&lt;int, int&gt;, int&gt; matchedBoxesCount;</p>
  <p>I have populated it and when I iterate over it with:</p>
  <pre><code>for(auto it = matchedBoxesCount.cbegin(); it != matchedBoxesCount.cend(); ++it)
  {
    std::cout &lt;&lt; it-&gt;first.first &lt;&lt; &quot; &quot; &lt;&lt; it-&gt;first.second &lt;&lt; &quot; &quot; &lt;&lt; it-&gt;second  &lt;&lt; &quot;,&quot;;
  }
  </code></pre>
  <p>The result is:</p>
  <pre><code>0 0 168, 0 1 8, 0 2 7, 0 3 7, 0 4 1, 0 5 9, 3 0 6, 3 1 41, 3 2 1, 3 3 3, 3 5 4, 3 6 2, 4 0 22, 4 1 1, 4 2 45, 4 3 7, 4 5 3, 4 9 2
  </code></pre>
  <p>I would like to filter this map into a simple map of pairs based on the value field of the key pair.</p>
  <p>so based on highest value of each different first.first - so unique firsts 0, 3, 4</p>
  <p>0 0 168 - is highest for 0 first field</p>
  <p>3 1 41 - is highest for 3 first field</p>
  <p>4 2 45 - is highest for 4 first field</p>
  <p>copy these into a new map:</p>
  <pre><code>std::map&lt;int,int&gt; topScores;
  
  int prevValuefirst = -1;
  int currentMax = 0;
  
  for(auto it = matchedBoxesCount.cbegin(); it != matchedBoxesCount.cend(); ++it) {
          if (it-&gt;first.first == prevValuefirst){
              if(it-&gt;second &gt; currentMax){
                  currentMax = it-&gt;second;
                  topScores.at(prevValuefirst) = it-&gt;first.second;}
          } else {
              prevValuefirst = it-&gt;first.first;
              topScores[prevValuefirst] = it-&gt;first.second;
              currentMax = it-&gt;second;
          }
      }
  </code></pre>
  <p>it appears to work, but the map isn't sorted prior so this solution would fall over if a 'first.first' element appeared later in the list.</p>
  <p>Is there a better way to do this? Should a sort be applied prior to make sure?</p>
  <p>Thank you</p>