priority_queue in C++ STL

本文详细介绍了C++标准模板库中的priority_queue,包括其基本用法(如创建、插入、访问和删除元素),以及如何使用lambda函数和自定义比较函数进行额外的排序。还展示了如何在存储自定义类时,直接在类中定义比较操作符以适应priority_queue的需求。
摘要由CSDN通过智能技术生成

The `priority_queue` is a container adapter in the C++ Standard Template Library (STL) that provides a queue implementation based on priority. This means that elements are sorted according to their priority (by default, it's a max heap where the element with the highest priority comes first), and insertions occur at one end of the queue while removals occur at the other.

The `priority_queue` uses an underlying container (default is `vector`) to store elements and offers a set of functions to access and modify the queue. Let's delve into the basic usage and additional sorting methods for `priority_queue`.

Basic Usage

Including the Header

Firstly, to use `priority_queue`, you need to include the queue header:

#include <queue>

Creating a `priority_queue`

You can create a `priority_queue` as follows:

std::priority_queue<int> pq; // Default is a max heap

If you prefer a min heap, you can specify the second template parameter:

std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap;

Inserting Elements

To insert elements into the priority queue, use the `push` function:

pq.push(10);
pq.push(5);
pq.push(20);

 Accessing the Top Element

To access the top element of the queue (the element with the highest priority), use the `top` function:

int topElement = pq.top();

Deleting the Top Element

To remove the top element from the queue, use the `pop` function:

pq.pop();

Additional Sorting Methods

If you want to use a custom sorting method, you can provide a comparison function.

Using Lambda Functions
std::priority_queue<int, std::vector<int>, [](int a, int b) { return a > b; }> customQueue;
Using Function Objects
struct Compare {
    bool operator()(int a, int b) {
        return a > b;
    }
};

std::priority_queue<int, std::vector<int>, Compare> customQueue;

Here, `Compare` is a function object that defines an overloaded operator() to compare the priority of two elements. You can modify the implementation of the comparison function to meet specific sorting needs.

Customizing `priority_queue` with Classes or Structs(the most interetsing one)

As pointed out by the user, if you are using `priority_queue` to store custom classes or structs, you can define the comparison function or operator within the class or struct itself, without providing an additional comparison function in the `priority_queue` template parameters.

Here's an example of how to define a comparison operator within a class or struct for use in `priority_queue`:

#include <iostream>
#include <queue>

class CustomObject {
public:
    int value;

    // Constructor
    CustomObject(int val) : value(val) {}

    // Overload less than operator for priority definition
    bool operator<(const CustomObject& other) const {
        // Define the comparison rule as needed
        return value < other.value;
    }
};

int main() {
    // Priority queue with custom objects
    std::priority_queue<CustomObject> customQueue;

    // Insert elements
    customQueue.push(CustomObject(10));
    customQueue.push(CustomObject(5));
    customQueue.push(CustomObject(20));

    // Access and delete top element
    std::cout << "Top element: " << customQueue.top().value << std::endl;
    customQueue.pop();

    // Output remaining elements
    while (!customQueue.empty()) {
        std::cout << customQueue.top().value << " ";
        customQueue.pop();
    }

    return 0;
}

In this example, the `CustomObject` class overloads the less than operator to sort elements in the `priority_queue` based on the `value`. This approach makes it easier to use custom classes or structs and provides a clearer comparison logic.


In summary, `priority_queue` offers a convenient interface to implement priority-based queues and can be tailored to different sorting needs by providing custom comparison functions.

  • 14
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C++ STL中的priority_queue是一个优先队列,它是一个使用堆来实现的容器。它可以按照一定的优先级顺序存储元素,并且每次访问队首元素都是访问优先级最高的元素。 在使用priority_queue时,可以通过定义不同的比较函数来指定元素的优先级顺序。默认情况下,对于基本类型,默认是大顶堆,降序队列。也可以通过指定参数来实现小顶堆,升序队列。例如: priority_queue<int, vector<int>, greater<int>> q; //小顶堆,升序队列 priority_queue<int, vector<int>, less<int>> q; //大顶堆,降序队列 在对priority_queue进行操作时,可以使用push()函数向队列中插入元素,使用top()函数获取队首元素,使用pop()函数删除队首元素。 在自定义类型的优先队列中,可以重载运算符>或<来定义优先级。例如,可以重载operator>来定义小顶堆,即优先级较小的元素排在前面。示例代码如下: struct Node{ int x, y; Node(int a=0, int b=0): x(a), y(b) {} }; bool operator> (Node a, Node b){ if(a.x == b.x) return a.y > b.y; return a.x > b.x; } priority_queue<Node, vector<Node>, greater<Node>> q; q.push(Node(rand(), rand())); while(!q.empty()){ cout<<q.top().x<<' '<<q.top().y<<endl; q.pop(); } 总结来说,C++ STL中的priority_queue是一个使用堆实现的优先队列,可以按照指定的优先级顺序存储元素。可以通过定义不同的比较函数或重载运算符来指定优先级规则。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【总结】C++ 基础数据结构 —— STL之优先队列(priority_queue) 用法详解](https://blog.csdn.net/weixin_44668898/article/details/102132580)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Any Problem?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值