本文共 1119 字,大约阅读时间需要 3 分钟。
从sort的函数原型看出,sort函数所需要的参数是随机迭代器
templatevoid sort (RandomAccessIterator first, RandomAccessIterator last);
所以,sort支持对数组、vector的数据进行排序,不支持map的排序,因为map不支持随机迭代器,使用的是双向迭代器。所以如果要对map 中的val进行排序,需要把数据放入vector中。
#include "stdafx.h"#include#include #include
程序中用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 (paira,pair b){ return a.second>b.second ;}
最后将排序后的结果输出。
转载地址:http://yidmi.baihongyu.com/