//定義比較的函數(shù)
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;
}
簡述:通過調(diào)用max_element
函數(shù),給定其特定的比較方式,將會獲得在給定比較方式下得結(jié)果.上述代碼中,給定的比較方式是根據(jù)value
值進(jìn)行比較,相當(dāng)于重構(gòu)了<
號.將返回最大值.
使用匿名函數(shù)重構(gòu):
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【使用匿名函數(shù)】
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;
}
打印結(jié)果:
3 10 19 20
19,20
C++獲取map中value最大最小值對應(yīng)的鍵值對_普通網(wǎng)友的博客-CSDN博客_c++ map求最大值文章來源:http://www.zghlxwxcb.cn/news/detail-573552.html
C++ 匿名函數(shù)_mayue_csdn的博客-CSDN博客_c++ 匿名函數(shù)?文章來源地址http://www.zghlxwxcb.cn/news/detail-573552.html
到了這里,關(guān)于C++-map:獲取map中value最大值、最小值對應(yīng)的鍵值對的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!