http://classfoo.com/ccby/article/Q3jxC
// <queue> template < class T , class Container = vector < T >, class Compare = less < typename Container :: value_type > > class priority_queue ;
优先级队列 (Priority queue)是一个容器适配器(Container adaptor)类型,被特别设计使其第一个元素总是容器所包含的元素中按特定的严格弱序排序规则排序后最大的一个。
T
容器所包含的元素的类型。
在类模板内部,使用其别名为 value_type
的成员类型。
Container
底层的用于存储元素的容器的类型。
Compare
一个二元谓词,以两个元素为参数返回一个 bool
值。
可以是函数指针(Function pointer)类型或函数对象(Function object)类型。
priority_queue
的定义使得它类似一个堆(Heap),该堆只能获得它的最大堆元素(在 priority_queue
中即为队列头)。
priority_queue
通常被实现为容器适配器,即使用一个特定容器类的封装对象作为它的底层容器。priority_queue
提供了一系列成员函数用于操作它的元素,只能从容器“后面”提取 (Pop)元素,该元素也可认为是 priority_queue
的“顶部(Top)”。
用来实现优先级队列的底层容器必须满足顺序容器的所有必要条件。同时,它还必须提供以下语义的成员函数:
front()
push_back()
pop_back()
为了使内部始终保持堆结构,底层容器必须支持随机访问迭代器。这样,容器适配器内部就可以在适当的时候自动调用算法函数 std::make_heap
、std::push_heap
、std::pop_heap
。
满足上述条件的标准容器有 std::vector
及 std::deque
,如果未特别指定 priority_queue
的底层容器,标准容器 std::vector
将被使用。
Any sequence container with random access iterator and supporting operations front(), push_back() and pop_back() can be used to instantiate priority_queue. In particular, vector and deque can be used.
C++编程语言国际标准:ISO/IEC 14882:2011
成员类型 定义 value_type
第一个模板参数 T container_type
第二个模板参数 Container size_type
Container::size_type
reference
Container::reference
const_reference
Container::const_reference
Element access:
Capacity:
Modifiers:
综合 1
下面这个例子简单地介绍了 priority_queue
的常用使用方法:
#include <iostream> #include <queue> #include <functional> namespace ClassFoo { using namespace std ; void PriorityQueueExample1 () { priority_queue < int , vector <int> , greater <int> > foo1 ; priority_queue < int , vector <int> > foo2 ; int a []={ 1 , 3 , 4 , 2 , 5 , 0 , 6 }; for ( int i = 0 ; i < 7 ; i ++) { foo1 . push ( a [ i ]); foo2 . push ( a [ i ]); } cout << "foo1:" ; while (! foo1 . empty ()) { cout << foo1 . top ()<< " " ; foo1 . pop (); } cout << endl ; cout << "foo2:" ; while (! foo2 . empty ()) { cout << foo2 . top ()<< " " ; foo2 . pop (); } cout << endl ; } } int main () { ClassFoo :: PriorityQueueExample1 (); return 0 ; }
输出 :
foo1:0 1 2 3 4 5 6 foo2:6 5 4 3 2 1 0
栈 stack 容量适配器 底层的容器为: deque (默认) ,list,vector
队列 queue 容量适配器 底层的容器为: deque (默认) ,list
优先队列(二叉堆) priority_queue 容量适配器 底层的容器为: vector(默认) deque
说明:first element is always the greatest of the elements it contains, according to some strict weak ordering criterion; automatically calling the algorithm functions make_heap,push_heap and pop_heap.
前向列表 forward list 标准容器
双向列表 list 标准容器
向量 vector 标准容器 地址连续,大小可以动态变化的array
双端队列 deque 标准容器
说明 :通过随机迭代器和at[]成员函数可以直接访问元素,但因不能保证底层的元素是地址连续的,因此不允许对指针直接做偏移来访问元素。