iv67
iv67

Reputation: 4151

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

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

Upvotes: 4

Views: 8366

Answers (2)

songyuanyao
songyuanyao

Reputation: 172894

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

Upvotes: 8

Ravibhushan Kumar
Ravibhushan Kumar

Reputation: 397

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;
}

Upvotes: 3

Related Questions