map的两个值分别为key值和value值,map是按照key值进行排序的,无法直接对value排序。
可以将map的key和value组成一个新的结构PAIR,用一个PAIR型的vector存储map中的所有内容,对vecor按照value值进行排序。按顺序输出key。
//map按值排序 #include #include #include #include #include using namespace std; typedef pair PAIR; int cmp(const PAIR& x, const PAIR& y)//针对PAIR的比较函数 { return x.second > y.second; //从大到小 } int main() { map nmap; nmap["LiMin"] = 90; nmap["ZiLinMi"] = 79; nmap["BoB"] = 92; nmap.insert(make_pair("Bing",99)); nmap.insert(make_pair("Albert",86)); //把map中元素转存到vector中 vector vec(nmap.begin(),nmap.end()); sort(vec.begin(), vec.end(), cmp); //排序 for (size_t i = 0; i != vec.size(); ++i) { //输出 cout << vec[i].first <<" "< C++中如何给map按值排序_百度知道 //map按值排序 #include #include #include #include #include using namespace std; struct student{ string name; int score; }; typedef pair PAIR; int cmp(const PAIR& x, const PAIR& y)//针对PAIR的比较函数 { return x.second.score > y.second.score; //从大到小 } int main() { map 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 <first<<' '<<(it->second).score< vec(nmap.begin(),nmap.end()); cout <
C++中如何给map按值排序_百度知道
//map按值排序 #include #include #include #include #include using namespace std; struct student{ string name; int score; }; typedef pair PAIR; int cmp(const PAIR& x, const PAIR& y)//针对PAIR的比较函数 { return x.second.score > y.second.score; //从大到小 } int main() { map 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 <first<<' '<<(it->second).score< vec(nmap.begin(),nmap.end()); cout <
上一篇 VS C++基于OpenCV进行相机标定和使用
下一篇 176
版权所有 (c)2021-2022 MSHXW.COM
ICP备案号:晋ICP备2021003244-6号