c++优先队列 less和greater

本文详细介绍了 C++ 中的优先队列(priority_queue)及其两种主要排列方式:less 和 greater。通过具体示例展示了 less 模式下优先输出较大数值,而 greater 模式下则优先输出较小数值的特点,并提供了自定义比较操作符的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++  中的容器 优先队列(priority_queue) 主要有两种排列方式  默认的less 和  greater

less 表示容器中的数据是 由大到小进行排列的

greater 表示容器中的数据是 由小到大进行排列的

那么也就意味着  less模式下,优先输出的较大的数值, greater模式下优先输出的较小的数值;

如下示例:

#include <functional>
#include <queue>
#include <vector>
#include <iostream>
 
template<typename T> void print_queue(T& q) {
    while(!q.empty()) {
        std::cout << q.top() << " ";
        q.pop();
    }
    std::cout << '\n';
}
 
int main() {
    std::priority_queue<int> q;
 
    for(int n : {1,8,5,6,3,4,0,9,7,2})
        q.push(n);
 
    print_queue(q);
 
    std::priority_queue<int, std::vector<int>, std::greater<int> > q2;
 
    for(int n : {1,8,5,6,3,4,0,9,7,2})
        q2.push(n);
 
    print_queue(q2);
 }

输出:

9 8 7 6 5 4 3 2 1 0  // less
0 1 2 3 4 5 6 7 8 9   //greater

可以对自定义操作符(>或 <)

struct node
{
    bool operator< (const node n1, const node n2)
    {
        return n1.priority < n2.priority;
    }
    int priority;
    int value;
}; 
struct node
{
    bool operater < (const struct node &k)
    const{
        priority < k.priority;
    }
    int priority, value;
}     //两种自定义方式是等价的

 

 

转载于:https://my.oschina.net/lCQ3FC3/blog/828571

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值