5.map排序

2021-04-24  本文已影响0人  lxr_
#include<iostream>
using namespace std;

#include<map>

//自定义数据类型必须使用仿函数指定排序规则

//使用仿函数指定排序规则
class MyCompare
{
public:
    bool operator()(int v1, int v2)const//加const设置仿函数为常函数,避免修改成员属性的值,加成员属性mutable可以在常函数中修改
    {
        return v1 > v2;
    }
};

void Print(map<int, int,MyCompare> m)
{
    for (map<int, int,MyCompare>::iterator it = m.begin(); it != m.end(); it++)
    {
        cout << "key=" << it->first << "\t" << "value=" << it->second << endl;
    }
}
void test0501()
{
    map<int, int,MyCompare> m;

    m.insert(make_pair(1, 4520));
    m.insert(make_pair(23, 230));
    m.insert(make_pair(234, 10));
    m.insert(make_pair(43, 340));
    m.insert(make_pair(43, 450));
    m.insert(make_pair(5, 40));
    
    Print(m);//默认自动降序排列
}

int main()
{
    test0501();

    system("pause");
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读