priority_queue自定义类型:只能重载运算符<,或者写仿函数对象

链接

其中结构体,类中的判断函数只能是 const后缀函数(常函数);

priority_queue <int,vector<int>,greater<int> > q;
//降序队列
priority_queue <int,vector<int>,less<int> >q1;

//greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。
// 其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)

//方法1
struct tmp1 //运算符重载<
{
    int x;
    tmp1(int a) {x = a;}
    bool operator<(const tmp1& a) const
    {
        return x < a.x; //大顶堆
    }
};

//方法2
struct tmp2 //重写仿函数
{
    bool operator() (tmp1 a, tmp1 b) const
    {
        return a.x < b.x; //大顶堆
    }
};

//类
class  tmp3 {
public:
    int a;
    int c;
    tmp3(int d,int x):a(d),c(x){};
    bool operator<(const tmp3 &one)  const 
    {
        return c>one.c;
    }
};
int main() {
    priority_queue<tmp1> t1;
    tmp1 a(5);
    tmp1 d(6);
    t1.push(a);
    t1.push(d);
    priority_queue<tmp3> t;
    tmp3 q1(56,5);
    tmp3 q2(5,5);
    tmp3 q3(56,51);
    t.push(q1);
    t.push(q2);
    return 0;
}

全部评论

相关推荐

11-04 19:05
已编辑
东莞城市学院 单片机
不知道怎么取名字_:你这个要实习两年?哪有这么久的,感觉就是即使你毕业了,但还按实习的话,是不是不用给你缴社保公积金啥的
点赞 评论 收藏
分享
10-17 23:18
已编辑
西北农林科技大学 Web前端
独行m:给25可以试试,但他只能给12,那就是纯纯的事精
秋招,不懂就问
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务