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

#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;
    }


}
默认情况下,map是按照键(key)的严格弱序关系(strict weak ordering)进行排序的。例如,如果map的键是整数类型,那么它们会按照从小到大的顺序进行排序。如果map的键是字符串类型,那么它们会按照字典序进行排序。 如果你想要按照其他方式进行排序,可以自定义比较函数(comparator)。比较函数是一个用于比较两个元素大小的函数,它接受两个元素作为参数,并返回一个bool值,表示它们的大小关系。 下面是一个例子,演示如何使用自定义比较函数对map进行排序: ```c++ #include <iostream> #include <map> #include <string> bool sortByValue(const std::pair<int, std::string>& a, const std::pair<int, std::string>& b) { return a.second < b.second; } int main() { std::map<int, std::string> myMap = {{1, "one"}, {2, "two"}, {3, "three"}, {4, "four"}, {5, "five"}}; // 使用自定义比较函数进行排序 std::vector<std::pair<int, std::string>> vec(myMap.begin(), myMap.end()); std::sort(vec.begin(), vec.end(), sortByValue); // 输出排序结果 for (auto& pair : vec) { std::cout << pair.first << " " << pair.second << std::endl; } return 0; } ``` 在这个例子中,我们定义了一个名为sortByValue的比较函数,用于按照值(value)的字典序进行排序。我们将map转换为一个vector,并使用std::sort函数和自定义比较函数进行排序。最后,我们遍历排序后的vector,并输出键和值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值