Find max values in a map from key pair first

Viewed 46

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.

I have a map created:

std::map<std::pair<int, int>, int> matchedBoxesCount;

I have populated it and when I iterate over it with:

for(auto it = matchedBoxesCount.cbegin(); it != matchedBoxesCount.cend(); ++it)
{
  std::cout << it->first.first << " " << it->first.second << " " << it->second  << ",";
}

The result is:

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

I would like to filter this map into a simple map of pairs based on the value field of the key pair.

so based on highest value of each different first.first - so unique firsts 0, 3, 4

0 0 168 - is highest for 0 first field

3 1 41 - is highest for 3 first field

4 2 45 - is highest for 4 first field

copy these into a new map:

std::map<int,int> topScores;

int prevValuefirst = -1;
int currentMax = 0;

for(auto it = matchedBoxesCount.cbegin(); it != matchedBoxesCount.cend(); ++it) {
        if (it->first.first == prevValuefirst){
            if(it->second > currentMax){
                currentMax = it->second;
                topScores.at(prevValuefirst) = it->first.second;}
        } else {
            prevValuefirst = it->first.first;
            topScores[prevValuefirst] = it->first.second;
            currentMax = it->second;
        }
    }

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.

Is there a better way to do this? Should a sort be applied prior to make sure?

Thank you

0 Answers
Related