c++优先队列(priority_queue)用法详解

既然是队列那么先要包含头文件#include <queue>, 他和queue不同的就在于我们可以自定义其中数据的优先级, 让优先级高的排在队列前面,优先出队

优先队列具有队列的所有特性,包括基本操作,只是在这基础上添加了内部的一个排序,它本质是一个堆实现的

和队列基本操作相同:

  • top 访问队头元素
  • empty 队列是否为空
  • size 返回队列内元素个数
  • push 插入元素到队尾 (并排序)
  • emplace 原地构造一个元素并插入队列
  • pop 弹出队头元素
  • swap 交换内容

定义:priority_queue<Type, Container, Functional>
Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆
一般是:

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

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

  1. 基本类型例子:
#include<iostream>
#include <queue>
using namespace std;
int main() 
{
    //对于基础类型 默认是大顶堆
    priority_queue<int> a; 
    //等同于 priority_queue<int, vector<int>, less<int> > a;
    
  
    priority_queue<int, vector<int>, greater<int> > c;  //这样就是小顶堆
    priority_queue<string> b;

    for (int i = 0; i < 5; i++) 
    {
        a.push(i);
        c.push(i);
    }
    while (!a.empty()) 
    {
        cout << a.top() << ' ';
        a.pop();
    } 
    cout << endl;

    while (!c.empty()) 
    {
        cout << c.top() << ' ';
        c.pop();
    }
    cout << endl;

    b.push("abc");
    b.push("abcd");
    b.push("cbd");
    while (!b.empty()) 
    {
        cout << b.top() << ' ';
        b.pop();
    } 
    cout << endl;
    return 0;
}

输出

4 3 2 1 0
0 1 2 3 4
cbd abcd abc

2.pari的比较,先比较第一个元素,第一个相等比较第二个

#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() 
{
    priority_queue<pair<int, int> > a;
    pair<int, int> b(1, 2);
    pair<int, int> c(1, 3);
    pair<int, int> d(2, 5);
    a.push(d);
    a.push(c);
    a.push(b);
    while (!a.empty()) 
    {
        cout << a.top().first << ' ' << a.top().second << '\n';
        a.pop();
    }
}

输出

2 5
1 3
1 2

3.对于自定义类型

#include <iostream>
#include <queue>
using namespace std;

//方法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) 
    {
        return a.x < b.x; //大顶堆
    }
};

int main() 
{
    tmp1 a(1);
    tmp1 b(2);
    tmp1 c(3);
    priority_queue<tmp1> d;
    d.push(b);
    d.push(c);
    d.push(a);
    while (!d.empty()) 
    {
        cout << d.top().x << '\n';
        d.pop();
    }
    cout << endl;

    priority_queue<tmp1, vector<tmp1>, tmp2> f;
    f.push(c);
    f.push(b);
    f.push(a);
    while (!f.empty()) 
    {
        cout << f.top().x << '\n';
        f.pop();
    }
}

输出

3
2
1

3
2
1
<think>嗯,用户让我介绍一下C++中的优先级队列。我需要先回忆一下相关的知识,然后组织语言,确保解释清楚。首先,优先级队列在C++的标准模板库(STL)里是存在的,对吧?它属于容器适配器的一种,通常基于堆结构实现。那它和普通队列有什么区别呢?对了,普通队列是先进先出,而优先级队列则是元素按优先级出队,优先级高的先出。 接下来,我需要说明它的基本用法。比如,如何声明一个优先级队列。记得要包含头文件<queue>,然后使用std::priority_queue模板类。默认情况下,它使用std::vector作为底层容器,比较函数是std::less,也就是最大元素在顶部。比如,std::priority_queue<int> pq; 这样的声明。 然后,用户可能需要知道如何自定义比较函数或者使用自定义的数据类型。比如,如果想要最小堆,就需要传入std::greater作为比较函数。这时候需要这样写:std::priority_queue<int, std::vector<int>, std::greater<int>> pq;。这里模板参数有三个,第二个是底层容器,第三个是比较器。 还有,当元素是自定义结构体或类时,需要重载比较运算符或者提供仿函数。比如,定义一个结构体Task,包含优先级和描述,然后为它提供operator<或者创建一个比较函数对象。这时候可能需要详细说明如何正确实现这些比较操作,以避免编译错误。 另外,常用的成员函数有哪些呢?比如push()插入元素,top()访问顶部元素,pop()移除顶部元素,empty()检查是否为空,size()获取元素数量。这些都需要逐一解释,并给出示例代码片段。 可能用户还会关心时间复杂度的问题。插入和删除操作的时间复杂度通常是O(log n),而访问顶部元素是O(1)。这些性能特点对于选择数据结构很重要,特别是在处理大数据量时。 应用场景方面,优先级队列常用于任务调度、Dijkstra算法、哈夫曼编码等需要按优先级处理元素的场合。比如,在操作系统中调度进程,每次选择优先级最高的进程运行,这时候优先级队列就很合适。 还需要注意一些常见的陷阱。比如,当使用自定义比较器时,如果比较逻辑写反了,可能导致最大堆变成最小堆或者相反。另外,迭代器访问的限制,因为优先级队列不提供遍历功能,只能访问顶部元素。 总结一下,回答的结构应该包括:优先级队列的定义、与普通队列的区别、基本用法、自定义比较方法、常用成员函数、时间复杂度、应用场景以及注意事项。这样用户就能全面了解C++中的priority_queue了。在解释过程中,尽量用简洁的代码示例和实际例子来帮助理解,避免过于抽象的描述。</think>C++ 中的优先级队列是一种容器适配器,属于标准模板库 (STL) 的一部分。它基于堆数据结构实现,允许元素按特定优先级顺序出队(默认最大值优先)。以下是详细介绍: --- ### 一、基本特性 1. **定义** ```cpp #include <queue> std::priority_queue<T> pq; // 默认最大堆 ``` 2. **底层结构** - 默认使用 `vector` 作为底层容器 - 通过堆算法维护元素顺序 3. **操作复杂度** - 插入 (`push`): $O(\log n)$ - 删除 (`pop`): $O(\log n)$ - 访问顶部元素 (`top`): $O(1)$ --- ### 二、核心用法 #### 1. 基本操作示例 ```cpp std::priority_queue<int> pq; pq.push(3); // 插入元素 pq.push(1); pq.push(4); std::cout << pq.top(); // 输出 4 (当前最大值) pq.pop(); // 移除顶部元素 ``` #### 2. 创建最小堆 ```cpp std::priority_queue<int, std::vector<int>, std::greater<int>> min_heap; // 使用 greater 比较器实现升序排列 ``` --- ### 三、自定义数据类型 当存储自定义类型时,需定义比较规则: #### 方法 1:重载运算符 ```cpp struct Task { int priority; std::string desc; bool operator<(const Task& other) const { return priority < other.priority; // 最大堆 } }; std::priority_queue<Task> task_queue; ``` #### 方法 2:自定义比较器 ```cpp struct CompareTask { bool operator()(const Task& a, const Task& b) { return a.priority > b.priority; // 最小堆 } }; std::priority_queue<Task, std::vector<Task>, CompareTask> custom_pq; ``` --- ### 四、典型应用场景 1. **任务调度** 处理高优先级任务(如操作系统进程调度) 2. **算法应用** - Dijkstra 最短路径算法 - 哈夫曼编码 - 合并 K 个有序链表 3. **实时系统** 处理紧急事件队列 --- ### 五、注意事项 1. **不可遍历** 只能通过 `top()` 访问顶部元素 2. **稳定性问题** 相同优先级的元素不保证先进先出 3. **内存效率** 相比 `set/multiset` 更节省内存,但无法快速查找任意元素 --- ### 六、代码示例(自定义类型) ```cpp #include <queue> #include <string> #include <iostream> struct Student { std::string name; int score; bool operator<(const Student& other) const { return score < other.score; // 按分数降序排列 } }; int main() { std::priority_queue<Student> students; students.push({"Alice", 85}); students.push({"Bob", 92}); students.push({"Charlie", 78}); while (!students.empty()) { auto top = students.top(); std::cout << top.name << ": " << top.score << "\n"; students.pop(); } /* 输出: Bob: 92 Alice: 85 Charlie: 78 */ } ``` --- 通过这种结构化的实现,C++ 优先级队列为需要按特定顺序处理元素的场景提供了高效的解决方案。实际使用时需根据需求选择合适的比较器类型和底层容器。
评论 98
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值