How to find Max value of second element of std::pair in std::vector?

Viewed 5092

I have vector of pairs in this order {{label, probability},{label, probability}}. I want to get the pair which has the maximum value of probability. Here's my attempt to accomplish that, but instead of getting the max value of probability, it returns the max value of the label string. e.g. label dog is the largest value because of alphabet order.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int main()
{
    std::vector<std::pair<std::string, float>> pairs;
    pairs = {{"apple",34.785}, {"banana",67.8467}, {"dog", 13.476}, {"cat",56.486}};

    const auto p = max_element(pairs.begin(), pairs.end());
    auto label = p->first;
    auto prob = p->second;

    std::cout<<label<<" "<<prob;
}

Output : dog 13.476

2 Answers

You need to provide a customized comparator to max_element, e.g.

max_element(pairs.begin(), 
            pairs.end(), 
            [](const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; });

Otherwise, std::max_element will use the operator< of std::pair as the comparator, which will check both the two elements of std::pair.

Note : works on C++14 and higher

LIVE

You can do this by custom comparator function.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

bool compare(std::pair<std::string, float> p1, std::pair<std::string, float> p2) {
    return p1.second<p2.second;
}

int main()
{
    std::vector<std::pair<std::string, float>> pairs;
    pairs = {{"apple",34.785}, {"banana",67.8467}, {"dog", 13.476}, {"cat",56.486}};

    const auto p = max_element(pairs.begin(), pairs.end(), compare);
    auto label = p->first;
    auto prob = p->second;

    std::cout<<label<<" "<<prob;
}
Related