根據value值對map進行排序

今天在做筆試題的時候發現需要根據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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章