如何在std::map中找到所有具有最大值C++的键
How to find all keys in std::map having maximum values C++?
例如,给定一个地图
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;
}
相关文章:
- 在MSDOS编译器上,用大于最大值的值初始化int时输出混乱
- 我无法显示包含整数最大值的索引. 但我可以显示数组中整数的最高值
- 在 openCV 矩阵中查找列最大值的索引和值
- 获取两个最大值的索引
- 找到稀疏矩阵(特征)最大值的有效方法
- 如何使用 c++ API 获取秩 3 张量流::张量的最大值的索引
- 当输入高于最大值的值时,如何将 QSpinBox 的值设置为 max
- 限制 std::给定最小值和最大值的矢量
- 具有最小值和最大值的多维背包
- 比较最小值/最大值的浮点数(浮点数或双精度数)
- 为什么从矩阵中获取最大值的函数建议 ->无法将 'int (*)[C]' 转换为 'int (*)[0]
- 如何返回指向链接列表中最大值的指针
- 返回最大值的索引
- 类型 *阵列的最小或最大值的类功能 *
- 用于在具有更新查询的二维矩阵中查找最大值的最佳数据结构
- 性能:在 ARR(允许平局)中查找最大值的索引
- 如何使用函数参数中的int指针来获取2d数组中最大值的索引并返回指针
- Linux C++ 创建具有最大值的信号量
- C++ 在 2D std::vector 中查找最大值的位置
- 返回最大值的索引