C++map如何按值排序
阿新 • • 發佈:2018-11-01
因為sort函式只能排序類似vector這樣的類,map是不能排序的。所以需要將map轉換為vector表示,那就需要pair
//map資料按照值來排序
void MapSortOfValue(vector<pair<int,string> >& vec,map<string,int>& m)
{
for (map<string, int>::iterator it = m.begin(); it != m.end(); it++)
vec.push_back(make_pair(it->second, it->first));
sort(vec.begin(), vec.end());
}
sort預設按照first從小到大排序。
例子如下:
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
//map資料按照值來排序
void MapSortOfValue(vector<pair<int,string> >& vec,map<string,int>& m)
{
for (map<string, int>::iterator it = m.begin(); it != m.end(); it++)
vec.push_back(make_pair(it->second, it->first));
sort(vec.begin(), vec.end());
}
int main()
{
vector<pair<int, string> > vec;
map<string, int> m;
m["ABC"] = 4;
m["ACB"] = 2;
m["CDB"] = 5;
m["ADB"] = 1;
cout << "排序前" << endl;
for (map<string, int>::iterator it = m.begin(); it != m.end(); it++)
cout << it->first.c_str() << " " << it->second << endl;
cout << "---------------------" << endl;
MapSortOfValue(vec, m);
cout << "排序後" << endl;
for (vector<pair<int, string> >::iterator it = vec.begin(); it != vec.end(); it++)
cout << it->first << " " << it->second.c_str() << endl;
return 0;
}
輸出結果如圖: