C++数据结构 之 优先队列_Priority Queue
来源:互联网 发布:数据透视图显示百分比 编辑:程序博客网 时间:2024/06/07 06:02
C++数据结构 之 优先队列_Priority Queue
源代码只包含头文件
注:需要C++11的支持
一、优先队列优先
队列的思想和队列是不同的,并不是先进先出,元素在入队列之后,有一个排序的过程:按照优先级,谁的优先级高就排在前面。但它的结构和队列类似。
它支持如下几个操作:
1、push (入队列):将元素从队列的末尾压入队列。
2、pop (出队列):将元素从队列的首位从元素取出。
3、top 返回最首位的元素,但是不出队列。
二、源代码:
#ifndef PRIORITY_QUEUE_H#define PRIORITY_QUEUE_H#include <vector>#include <algorithm>#include <functional>using std::make_heap;using std::pop_heap;using std::push_heap;template < typename T, typename Container = std::vector<T>, typename Compare = std::less<typename Container::value_type>> class Priority_Queue { public: typedef typename Container::size_type size_type; typedef typename Container::value_type value_type; typedef typename Container::const_reference const_reference; public: Priority_Queue() = default; Priority_Queue(const Priority_Queue &s) : c(s.c), comp(s.comp){} Priority_Queue& operator=(const Priority_Queue &s) { c = s.c; comp = s.comp; return *this; } template<class T> Priority_Queue(T First, T Last) : c(First, Last), comp() { make_heap(c.begin(), c.end(), comp); } Priority_Queue(const Container& cont) : c(cont) { make_heap(c.begin(), c.end(), comp); } Priority_Queue(const Compare& cmp, const Container& cont) : comp(cmp), c(cont) { make_heap(c.begin(), c.end(), comp); } ~Priority_Queue() = default; void push(value_type&& x) { c.push_back(move(x)); push_heap(c.begin(), c.end(), comp); } void push(const value_type& x) { c.push_back(x); push_heap(c.begin(), c.end(), comp); } const_reference& top() const { return c.front(); } void pop() { pop_heap(c.begin(), c.end(), comp); c.pop_back(); } bool empty() const { return c.empty(); } size_type size() const { return c.size(); } private: Container c; Compare comp;};#endif // !PRIORITY_QUEUE_H
注解:
本优先队列是基于vector(向量)实现的,并作用在heap(堆)上,以实现排序目的。Compare是一个比较子,它是按照数据类型的less函数对象实现的,从而确定了优先级。
0 0
- C++数据结构 之 优先队列_Priority Queue
- 数据结构之队列queue
- 数据结构之优先队列
- 数据结构之优先队列
- Java 数据结构之 Queue(队列)
- STL之stack,queue,优先队列
- STL之stack,queue,优先队列
- STL之优先队列priority queue
- C#数据结构之优先队列
- 数据结构 之 priority_queue 优先队列
- 数据结构之---优先队列(堆)
- 【数据结构】【C++STL】FIFO队列&优先队列
- priority queue 优先队列
- priority queue 优先队列
- 优先队列priority queue
- 基础queue优先队列
- STL 之 stack&queue&priority_queue 栈,队列与优先队列
- STL之栈stack,队列queue以及优先队列
- Java反射机制详解
- Docker挂载主机目录Docker访问出现Permission denied的解决办法
- 为图片添加文字
- Android Canvas绘图详解(图文)
- 摄像机的工作原理
- C++数据结构 之 优先队列_Priority Queue
- 快速集成QQ分享
- PET/CT图像的纹理特征提取
- hello
- 运行React Native示例出现null is not an object (evaluating 'this.state.text')
- HDU 1576 A/B(拓展欧几里得,模板题)
- html5移动端开发
- Android ViewPager的切换动画效果PageTransformer
- EXC_BAD_ACCESS