From: Ran Yi <42791146+i-Yirannn@users.noreply.github.com> Date: Fri, 31 Aug 2018 00:00:04 +0000 (+0800) Subject: Update priority_queue.md X-Git-Url: http://git.osdn.net/view?a=commitdiff_plain;h=755da5949c3c0e7ef32288e4aa44e3ad609e072f;p=oi-wiki%2Fmain.git Update priority_queue.md --- diff --git a/docs/ds/stl/priority_queue.md b/docs/ds/stl/priority_queue.md index 3ada50f0..d2a9da45 100644 --- a/docs/ds/stl/priority_queue.md +++ b/docs/ds/stl/priority_queue.md @@ -1 +1,52 @@ -Nothing much here now... \ No newline at end of file +### std :: priority_queue + +```cpp +#include // std :: priority_queue +// using namespace std; 推荐根据不同的使用分别using,而不是直接using std; 为了方便区别与pb_ds, +// 本文里的所有优先队列都会加上命名空间 +std :: priority_queue +/* + * T : 储存的元素类型 + * Container : 储存的容器类型,且要求满足顺序容器的要求、随机访问迭代器的要求、拥有 + * front()/push_back()/pop_back()三个函数,标准容器中 std :: vector / std :: deque满足这些要求 + * Compare : 提供严格的弱序比较类型 + * priority_queue是按照元素优先级大的在堆顶,根据operator < 的定义,默认是大根队,我们可以利用 + * greater(若支持),或者自定义类的小于号重载实现排序,注意 : 只支持小于号重载而不支持其他比较符号的重 + * 载 + */ +// 构造方式 : +std :: priority_queue; +std :: priority_queue> // C++11前,vector" ">双引号位置必须要有空格 +std :: priority_queue, greater> //注意 :不可跳过容器参数而直接传入比较类 +``` + +##### 成员函数 : + +1. ```top()```: 访问栈顶元素 常数复杂度 +2. ```empty()```: 检查底层的容器是否为空 常数复杂度 +3. ```size()```: 返回底层容器的元素数量 常数复杂度 +4. ```push()```: 插入元素,并对底层容器排序 最坏$\Theta(n)$ 均摊$\Theta(\log(n))$ +5. ```pop()```: 删除第一个元素 最坏$\Theta(\log(n))$ + +由于```std :: priority_queue```原生不支持```modify()``` /```join()```/```erase()```故不做讲解。 + +##### 示例 : + +```cpp + q1.push(1); + // 堆中元素 : [1]; + for(int i = 2; i <= 5; i ++ ) q1.push(i); + // 堆中元素 : [1, 2, 3, 4, 5]; + std :: cout << q1.top() << std :: endl; + // 输出结果 : 5; + q1.pop(); + std :: cout << q1.size() << std :: endl; + // 输出结果 :4 + // 堆中元素 : [1, 2, 3, 4]; + q1.push(10); + // 堆中元素 : [1, 2, 3, 4, 10]; + std :: cout << q1.top() << std :: endl; + // 输出结果 : 10; + q1.pop(); + // 堆中元素 : [1, 2, 3, 4]; +```