//map按值排序
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
struct student{
string name;
int score;
};
typedef pair<string, student> PAIR;
int cmp(const PAIR& x, const PAIR& y)//针对PAIR的比较函数
{
return x.second.score > y.second.score; //从大到小
}
int main() {
map<string,student> nmap;
student stu;
stu.name = "LiMin";
stu.score = 90;
nmap.insert(make_pair(stu.name, stu));
stu.name = "ZiLinMi";
stu.score = 79;
nmap.insert(make_pair(stu.name, stu));
stu.name = "BoB";
stu.score = 92;
nmap.insert(make_pair(stu.name, stu));
stu.name = "Bing";
stu.score = 99;
nmap.insert(make_pair(stu.name, stu));
stu.name = "Albert";
stu.score = 86;
nmap[stu.name] = stu;
cout <<endl<< "map:"<<endl;
for(auto it = nmap.begin(); it != nmap.end(); it++){
cout<<it->first<<' '<<(it->second).score<<endl;
}
// 把map中元素转存到vector中
vector<PAIR> vec(nmap.begin(),nmap.end());
cout <<endl<< "排序前:"<<endl;
for (size_t i = 0; i != vec.size(); ++i) { //输出
cout << vec[i].first <<" "<<vec[i].second.score<<endl;
}
// 排序
sort(vec.begin(), vec.end(), cmp);
cout <<endl<< "排序后vec1:"<<endl;
for (size_t i = 0; i != vec.size(); ++i) { //输出
cout << vec[i].first <<" "<<vec[i].second.score<<endl;
}
cout <<endl<< "排序后vec2:"<<endl;
// 迭代器
for (auto it = vec.begin(); it != vec.end(); it++) { //输出
cout << (*it).first <<" "<<(*it).second.score<<endl;
}
return 0;
}