如何在std::map中找到所有具有最大值C++的键

How to find all keys in std::map having maximum values C++?

本文关键字:最大值 的键 C++ std map      更新时间:2023-10-16

例如,给定一个地图

std::map<char, int> map{{'a', 5}, {'b', 3}, {'c', 2}, {'d', 5}};

我想输出键'a''d',因为它们在map中都有最大值。我该怎么做?

#include <iostream>
#include <map>
int main()
{
std::map<char, int> map{{'a', 5}, {'b', 3}, {'c', 2}, {'d', 5}};
// ???
}

您可以使用multimap+equal_range查询,该查询是为最高密钥调用的-可以通过rbegin方法提取:

std::map<char,int> m{{'a',2},{'b',3},{'c',5},{'d',5}};
std::multimap<int,char> m2;
for (auto&& i : m)
m2.insert(std::make_pair(i.second,i.first));
auto it = m2.rbegin(); // get the elem with the highest key
auto range = m2.equal_range(it->first);
for (auto it = range.first; it != range.second; ++it)
std::cout << it->first << ", " << it->second << std::endl; 

作为输出,您将获得:

// 5 d
// 5 c

您应该找到最大数量,然后收集具有该值的密钥。

这允许您使用最少的内存量(您不必复制所有内容,只复制结果(,并且应该更快,因为您不需要"复制";排序";所有内容(通过使用另一个std::*map/std::*set对象(或插入到另一个容器或从另一个集装箱中移除。

std::vector<char> maxValueKeys(const std::map<char, int>& input) {
// Case when no data is present
if (input.empty()) {
return {};
}
// Find maximum value
int max_value = input.begin()->second;
for (const auto& entry : input) {
if (entry.second > max_value) {
max_value = entry.second;
}
}
// Find all keys with maximum value
std::vector<char> keys;
for (const auto& entry : input) {
if (entry.second == max_value) {
keys.push_back(entry.first);
}
}
return keys;
}