如何在std::vector中找到std::pair的第二个元素的最大值?
How to find Max value of second element of std::pair in std::vector?
我有成对的向量,顺序为 {{label, probability},{label, probability}}。我想得到概率最大的一对。这是我尝试实现的,但不是获得概率的最大值,而是 returns 标签字符串的最大值。例如由于字母顺序,label dog 是最大值。
#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;
}
输出:dog 13.476
您需要为 max_element
提供自定义比较器,例如
max_element(pairs.begin(),
pairs.end(),
[](const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; });
否则,std::max_element
will use the operator<
of std::pair
作为比较器,它将检查std::pair
的两个元素。
注意:适用于 C++14 及更高版本
您可以通过自定义比较函数来完成此操作。
#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;
}
我有成对的向量,顺序为 {{label, probability},{label, probability}}。我想得到概率最大的一对。这是我尝试实现的,但不是获得概率的最大值,而是 returns 标签字符串的最大值。例如由于字母顺序,label dog 是最大值。
#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;
}
输出:dog 13.476
您需要为 max_element
提供自定义比较器,例如
max_element(pairs.begin(),
pairs.end(),
[](const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; });
否则,std::max_element
will use the operator<
of std::pair
作为比较器,它将检查std::pair
的两个元素。
注意:适用于 C++14 及更高版本
您可以通过自定义比较函数来完成此操作。
#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;
}