c++ map sort by value and sort by key(字典的遍历)

来源:互联网 发布:淘宝卖家一直不发货 编辑:程序博客网 时间:2024/04/30 06:12
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <queue>
#include <stack>
#include <map>
#define INF 123123123
#define MAX_INDEX 150
using namespace std;




struct node
{
    int a1,a2;
    bool operator < (const node &other) const
    {
        if ((a1<other.a1)
                ||(a1==other.a1 && a2<other.a2)
           )
        {
            return true;
        }
        return false;
    }
};
int cmp(const pair<node,int> &x,const pair<node,int> &y)
{
    return x.second < y.second;
}


void sortMapbyValue(map<node,int> &t_map,vector< pair<node,int> > &t_vec)
{
    for(map<node,int>::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()
{
    map<node,int> m_result;
    vector< pair<node,int> > v_result;
    node temp;
    temp.a1 = 1;
    temp.a2 = 2;
    m_result[temp] = 1;


    temp.a1 = 2;
    temp.a2 = 3;
    m_result[temp] = 4;


    temp.a1 = 1;
    temp.a2 = 3;
    m_result[temp] = 10;


    cout<<"sort by key :"<<endl<<endl;
    for(map<node,int>::iterator iter = m_result.begin(); iter != m_result.end(); iter++)
    {
        printf("m_result<%d,%d>=%d\n",iter->first.a1,iter->first.a2,iter->second);
    }


    sortMapbyValue(m_result,v_result);


    cout<<"sort by value :"<<endl<<endl;
    for(int i=0; i<v_result.size(); i++)
    {
        cout << "m_result<" << v_result[i].first.a1 << "," << v_result[i].first.a2 << ">=" << v_result[i].second << endl;
    }


}
0 0