C++-map:获取map中value最大值、最小值对应的键值对
2023-09-27 14:20:39 时间
//定义比较的函数
bool cmp_value(const pair<int, int> left,const pair<int,int> right){
return left.second < right.second;
}
int main(){
map<int, int> test;
//初始化
test.emplace(10, 5);
test.emplace(3, 17);
test.emplace(19, 20);
test.emplace(20, 15);
//输出按序排列的key值
for (auto it : test)
cout << it.first << " ";
cout << endl;
//i是迭代器 返回值为19-20
auto i= max_element(test.begin(),test.end(),cmp_value);
cout << i->first << i->second << endl;
}
简述:通过调用max_element
函数,给定其特定的比较方式,将会获得在给定比较方式下得结果.上述代码中,给定的比较方式是根据value
值进行比较,相当于重构了<
号.将返回最大值.
使用匿名函数重构:
int main(){
map<int, int> test;
//初始化
test.emplace(10, 5);
test.emplace(3, 17);
test.emplace(19, 20);
test.emplace(20, 15);
//输出按序排列的key值
for (auto it : test)
cout << it.first << " ";
cout << endl;
//i是迭代器 返回值为19-20【使用匿名函数】
auto i= max_element(map.begin(),map.end(),[](pair<char, int> left, pair<char,int> right) { return left.second < right.second; });
cout << i->first << "," << i->second << endl;
}
打印结果:
3 10 19 20
19,20
相关文章
- C/C++知识要点2——STL中Vector、Map、Set容器的实现原理
- 【转】C++ map的基本操作和使用
- C++第11周项目2(9)参考——污损的数字
- C++中构造函数什么时候会被调用(从本质上理解)
- c++11 中成员变量初始化的顺序
- [学习笔记]Java作用域变量申明和C、C++的差异性
- [第十一届蓝桥杯省赛C++B组]走方块
- 一、C++桌面开发引导
- 如何分析和提高大型项目(C/C++)的编译速度?(VS2015特有的:/LTCG:incremental选项)
- C/C++调用java---JNI常用函数
- C++ 关联容器之map插入相同键元素与查找元素操作
- C++中 使用数组作为map容器VAlue值的解决方法
- C++中的STL中map用法详解
- 详解C++ STL map 容器
- 【C++】int与string互转
- C++ unordered_map remove 实现哈希表移除