今天在做笔试题的时候发现需要根据value值对map进行排序,通过查资料发现其基本思路是通过讲map中的键值对转化存储到vector中进行排序得到的。
代码如下:
#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
int cmpValue( const pair<string, int>&x, const pair<string, int>&y )
{
return x.second > y.second;
}
void sortMapByValue( map<string, int>& sortmap, vector<pair<string, int> >& sortvector )
{
for( map<string, int>::iterator curr = sortmap.begin(); curr != sortmap.end(); curr++ )
sortvector.push_back( make_pair( curr->first, curr->second ) );
sort( sortvector.begin(), sortvector.end(), cmpValue );
}
int cmpIntAsc( int &x, int &y )
{
return x < y;
}
int main()
{
int m, n, temp1;
string temp2;
int min = 0, max = 0;
vector<int> v;
map<string, int> thing;
vector< pair< string,int> > Vector;
cin >> m >> n;
for( int i = 0; i < m; i++ )
{
cin >> temp1;
v.push_back( temp1 );
}
for( int i = 0; i < n; i++ )
{
cin >> temp2;
if( thing.count( temp2 ) == 0 )
thing[ temp2 ] = 1;
else
thing[ temp2 ] = thing[ temp2 ] + 1;
}
sortMapByValue( thing, Vector );
sort( v.begin(), v.end(), cmpIntAsc );
for( int i = 0; i < m; i++ )
cout << v[i] <<" ";
cout << "\n";
for(int i=0; i < Vector.size(); i++)
cout << Vector[i].first <<" : " << Vector[i].second << endl;
return 0;
}