c++ map按key或value的值分别进行排序

一、对key值进行特定的排序

map容器里面有两个值一个key一个是value,map<key,value>,其实map里面还有第三个参数,是一个类,用来对map的key进行排序的类,定义如下

template<class _Kty,
    class _Ty,
    class _Pr = less<_Kty>,
    class _Alloc = allocator<pair<const _Kty, _Ty> > >
    class map

less<_Kty>的代码

struct less
        : public binary_function<_Ty, _Ty, bool>
    {    // functor for operator<
    bool operator()(const _Ty& _Left, const _Ty& _Right) const
        {    // apply operator< to operands
        return (_Left < _Right);
        }
    };

那么根据上面的代码我们也可以写出一个greater类来让key按照降序排列

#include <iostream>
#include <string>
#include <map>
using namespace std;

typedef pair<string, int> PAIR;

struct greater
{   
    bool operator()(const string& _Left, const string& _Right) const
    {  
        return (_Left > _Right);
    }
};

int main()
{
    map<string, int,greater> ma;
    ma["Alice"] = 86;
    ma["Bob"] = 78;
    ma["Zip"] = 92;
    ma["Stdevn"] = 88;
    for (map<string, int>::iterator ite = ma.begin(); ite != ma.end(); ++ite)
    {
        cout << ite->first << " " << ite->second << endl;
    }
    getchar();
}

默认的排序和用greater进行的排序分别如下

以上就对key值进行了你想要的排序方式。

二、对value的值进行排序

因为map的模板里面没有对value的值进行排序的参数,所以只能借助sort函数,然而sort函数只能对vector,list,queue等排序,无法对map排序,那么就需要把map的值放入vector中在对vector进行排序,在对vector进行输出,从而间接实现了对map的排序。sort也有第三个参数,跟上面那个map类似,所以可以写一个类或者函数来将其排序。

#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;

typedef pair<string, int> PAIR;

bool cmp_val(const PAIR &left,const PAIR &right)
{
    return left.second < right.second;
}

int main()
{
    map<string, int> ma;
    ma["Alice"] = 86;
    ma["Bob"] = 78;
    ma["Zip"] = 92;
    ma["Stdevn"] = 88;
    vector<PAIR> vec(ma.begin(),ma.end());
    sort(vec.begin(),vec.end(),cmp_val);
    for (vector<PAIR>::iterator ite = vec.begin(); ite != vec.end(); ++ite)
    {
        cout << ite->first << " " << ite->second << endl;
    }
    getchar();
}

结果如下

 

这样就通过cmp_val函数对vector进行了排序,然后在将其输出即可。

如果感觉写函数过于繁琐也可以直接在sort里面用lambda表达式,代码如下

#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;

typedef pair<string, int> PAIR;

int main()
{
    map<string, int> ma;
    ma["Alice"] = 86;
    ma["Bob"] = 78;
    ma["Zip"] = 92;
    ma["Stdevn"] = 88;
    vector<PAIR> vec(ma.begin(),ma.end());
    sort(vec.begin(), vec.end(),[](const PAIR &left, const PAIR &right)
    {
        return left.second < right.second;
    });
    for (vector<PAIR>::iterator ite = vec.begin(); ite != vec.end(); ++ite)
    {
        cout << ite->first << " " << ite->second << endl;
    }
    getchar();
}

 

posted on 2016-04-04 22:20  邵开2013551816  阅读(8453)  评论(0编辑  收藏  举报