栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ std::map sort 如何按值排序 自定义比较函数 比较对象某个字段

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ std::map sort 如何按值排序 自定义比较函数 比较对象某个字段

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 < 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/433300.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号