C++11 map实现插入后按value自动排序
本质上还是使用了map自动按照key进行排序的原理,所以将value放入key中可实现按value排序#include<iostream>
#include<map>
#include<vector>
using namespace std;
struct CmpByValue {
bool operator()(const pair<int, int>& k1, const pair<int, int>& k2) {
return k1.second >= k2.second; //降序排序
}
};
int main(int argc, char const *argv[])
{
std::vector<int> arr={5,4,6,8,9};
map<pair<int, int>, int, CmpByValue> maps;
int index=0;
for(int num:arr){
// maps = num;
// maps = index++;
maps.insert(make_pair(make_pair(index++, num), num));
}
for(auto it:maps){
cout<<"["<<it.first.first<<", "<<it.first.second<<"]"<<it.second<<endl;
}
cout<<"==========================="<<endl;
maps.insert(make_pair(make_pair(index++, 7), 7)); //插入7
for(auto it:maps){
cout<<"["<<it.first.first<<", "<<it.first.second<<"]"<<it.second<<endl;
}
return 0;
}
文档来源:51CTO技术博客https://blog.51cto.com/u_14175378/3335983
页:
[1]