1. 程式人生 > >STL中map按照vaule來排序

STL中map按照vaule來排序

 map預設是按照鍵(key)排序的。很多時候我們需要按值(value)排序,靠map裡的演算法當然是不行的,STL中map結構實際運用時,有時需要我們通過<key,value>中的value來進行排序而不是使用預設的key,由於value值是有可能重複的,所以交換key和value不一定達到要求。這裡我們可以通過使用vector來實現這一轉換:

  1 把map結構中的資料放到vector中

  2 設定vector的排序演算法來實現通過value排序

#include<iostream>
#include<string>
#include<string.h>
#include<map>
#include<vector>
#include<algorithm>

using namespace std;

int cmp(const pair<string,double> &x,const pair<string,double> &y)
{
    return x.second > y.second;
}

void sortMapbyValue(map<string,double> &t_map,vector< pair<string,double> > &t_vec)
{
    for(map<string,double>::iterator iter = t_map.begin();iter != t_map.end(); iter ++)
    {
        t_vec.push_back(make_pair(iter->first,iter->second));
    }

    sort(t_vec.begin(),t_vec.end(),cmp);
}

int main(void)
{
    map<string,double> m_result;
    vector< pair<string,double> > v_result;

    m_result.insert(pair<string,double>("abc",20.33));
    m_result.insert(pair<string,double>("abd",22.33));
    m_result.insert(pair<string,double>("abe",21.33));
    m_result.insert(pair<string,double>("abf",19.33));

    cout<<"sort by key :"<<endl<<endl;
    for(map<string,double>::iterator iter = m_result.begin(); iter != m_result.end(); iter++)
    {
        cout<<iter->first<<"\t\t"<<iter->second<<endl;
    }

    sortMapbyValue(m_result,v_result);

    cout<<"sort by value :"<<endl<<endl;
    for(int i=0; i<v_result.size(); i++)
    {
        cout<<v_result[i].first<<"\t\t"<<v_result[i].second<<endl;
    }
}

執行結果: