C++ 自定义二元谓词函数的写法

对于优先级队列priority_queue,注意默认的是less函数,优先级队列是大数在队列头,若想要小数在队列头部,需要greater
但是对于自定义的二元谓词函数应该是重载()运算符,或者使用仿函数

struct cmp 
{
    bool operator()(pair<int, int>& a, pair<int, int>& b)
    {
        if (a.first == b.first)
            return a.second > b.second;
        else
            return a.second < b.second;
    }
};

int main()
{
    priority_queue<pair<int, int>, vector<pair<int,int>>, cmp> que;
}

对于set应该这么写:
需要注意的是set默认使用less得到的将是从小到大的排列,使用great得到的是从大到小的排列,这个和优先级队列相反

struct cmp 
{
    bool operator() (int a, int b) 
    {
        if (a < b)
            return true;
        else
            return false;
    }
};

int main()
{
    set<int, cmp> ss;
    multiset<int, greater<int>> ms;
    for (int i = 0; i < 10; i++)
    {
        ss.insert(i);
        ms.insert(i);
        ms.insert(i + 1);
    }
    for (int i : ss)
        cout << i << "  ";
    cout << endl;

    for (int i : ms)
        cout << i << "  ";
    cout << endl;
    system("pause");
}

对于map呢?
需要注意的是cmp函数是const函数,所以后面的const是必须要的
参考这个博客
[C/C++]map自定义比较函数

struct cmp
{
    bool operator() (int a, int b) const
    {
        if (a < b)
            return true;
        else
            return false;
    }
};


int main()
{
    map<int, int,cmp> mp;
    multimap<int, int,cmp> mmp;

    for (int i = 0; i < 10; i++)
        mp[i] = i;

    for (auto i : mp)
        cout << i.first << "   ";
    cout << endl;

    system("pause");
}

对于multimap则有点复杂,参考这个博客C++的multimap自定义key值

主要就是重载小于<运算符,注意这里实在类中重载的

#include<iostream>
#include<stdio.h>
#include<map>
class A
{
public:
    A(int a) :a_(a) {}
    bool operator<(A BObj) const {
        return a_<BObj.a_;
    }
private:
    int a_;
};
int main()
{
    std::multimap<A, std::string> mapTest;
    mapTest.insert(std::make_pair(A(4), "zsy"));
    mapTest.insert(std::make_pair(A(2), "qwe"));
    mapTest.insert(std::make_pair(A(1), "asd"));
    mapTest.insert(std::make_pair(A(3), "qwe"));
    auto it = mapTest.begin();
    for (; it != mapTest.end(); it++)
    {
        printf("%s\n", it->second.c_str());
    }
    system("pause");
    return 0;

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值