博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用sort对map的val值进行排序
阅读量:4213 次
发布时间:2019-05-26

本文共 1119 字,大约阅读时间需要 3 分钟。

从sort的函数原型看出,sort函数所需要的参数是随机迭代器

template 
void sort (RandomAccessIterator first, RandomAccessIterator last);

所以,sort支持对数组、vector的数据进行排序,不支持map的排序,因为map不支持随机迭代器,使用的是双向迭代器。所以如果要对map 中的val进行排序,需要把数据放入vector中。

#include "stdafx.h"#include 
#include
#include
#include
#include
using namespace std;int _tmain(int argc, _TCHAR* argv[]){
int a[]={
1,2,3,7,2,4,1,4,3,3,3,2}; vector
st(a,a+12);//vs版本较低,不支持直接赋值 map
hash; for(int temp:st) hash[temp]++; vector
> temp; for(auto p:hash) temp.push_back(p); sort(temp.begin (),temp.end(),[](pair
a,pair
b){ return a.second>b.second ;}); for(auto i=temp.begin ();i
first <<","<
second <

程序中用map对vector中数字出现的次数进行了统计,统计结果放在hash map中。现在想要将这些数字按出现频率高低进行排序,也就是按值进行排序。

首先将map中的数据放入vector<pair<int,int> > 类型的数组中,然后使用sort进行从大到小的排序。这里使用了lambda表达式来实现排序函数。vector中每个元素是pair类型的数据,比较a.second>b.second的大小来进行排序。(pair<int,int> a,pair<int,int> b)是输入参数,{return a.second>b.second ;}是函数体。
原函数是这样

bool (pair
a,pair
b){
return a.second>b.second ;}

最后将排序后的结果输出。

转载地址:http://yidmi.baihongyu.com/

你可能感兴趣的文章
ebay api - GetUserDisputes 函数
查看>>
ebay api GetMyMessages 函数
查看>>
手动12 - 安装php加速器 Zend OPcache
查看>>
set theme -yii2
查看>>
yii2 - 模块(modules)的view 映射到theme里面
查看>>
yii2 - controller
查看>>
yii2 - 增加actions
查看>>
php图像处理函数大全(缩放、剪裁、缩放、翻转、旋转、透明、锐化的实例总结)
查看>>
magento url中 uenc 一坨编码 base64
查看>>
强大的jQuery焦点图无缝滚动走马灯特效插件cxScroll
查看>>
Yii2.0 数据库查询
查看>>
yii2 db 操作
查看>>
mongodb group 有条件的过滤组合个数。
查看>>
关于mongodb的 数组分组 array group
查看>>
MongoDB新的数据统计框架介绍
查看>>
mongodb 增加全文检索索引
查看>>
mysql数据库主从同步的问题解决方法
查看>>
QC数据库表结构
查看>>
测试工具厂商的编程语言什么时候“退休”?
查看>>
资源监控工具 - Hyperic HQ
查看>>