C++/C++11中std::priority_queue的使用
std::priority_queue:在优先队列中,优先级高的元素先出队列,并非按照先进先出的要求,类似一个堆(heap)。其模板声明带有三个参数,priority_queue<Type, Container, Functional>, 其中Type为数据类型,Container为保存数据的容器,Functional为元素比较方式。Container必须是用数组实现的容器,比如 vector, deque. STL里面默认用的是vector. 比较方式默认用operator< , 所以如果把后面两个参数缺省的话,优先队列就是大顶堆,队头元素最大。
std::priority_queue: priority queues are a type of container adaptors, specifically designed such that its first element is always the greatest of the elements it contains, according to some strict weak ordering criterion. This context is similar to a heap, where elements can be inserted at any moment, and only the max heap element can be retrieved (the one at the top in the priority queue). Priority queues are implemented as container adaptors, which are classes that use an encapsulated object of a specific container class as its underlying container, providing a specific set of member functions to access its elements. Elements are popped from the "back" of the specific container, which is known as the top of the priority queue.
A priority queue is a queue data structure that has the particular property of being sorted by priority. You can decide what priority to give items depending on the data type.
下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:
#include "priority_queue.hpp"
#include <iostream>
#include <queue> // std::priority_queue
#include <string>
#include <vector>
#include <functional> // std::greater
#include <deque>
#include <list>//template < class T,
// class Container = vector<T>,
// class Compare = less<typename Container::value_type> >
//class priority_queue;///
// reference: http://www.cplusplus.com/reference/queue/priority_queue/
int test_priority_queue_1()
{
{ // std::priority_queue::push: Inserts a new element in the priority_queue.// The content of this new element is initialized to val. inserts element and sorts the underlying container// std::priority_queue::pop: Removes the element on top of the priority_queue, removes the top element,// effectively reducing its size by one. The element removed is the one with the highest value.// std::priority_queue::empty: Test whether container is emptystd::priority_queue<int> mypq;mypq.push(30);mypq.push(100);mypq.push(25);mypq.push(40);std::cout << "Popping out elements...";while (!mypq.empty()) {std::cout << ' ' << mypq.top();mypq.pop();}std::cout << '\n';
}{ // std::priority_queue::emplace: C++11, Adds a new element to the priority_queue.// This new element is constructed in place passing args as the arguments for its constructor.std::priority_queue<std::string> mypq;mypq.emplace("orange");mypq.emplace("strawberry");mypq.emplace("apple");mypq.emplace("pear");std::cout << "mypq contains:";while (!mypq.empty()) {std::cout << ' ' << mypq.top();mypq.pop();}std::cout << '\n';
}{// std::priority_queue::size: Returns the number of elements in the priority_queuestd::priority_queue<int> myints;std::cout << "0. size: " << myints.size() << '\n';for (int i = 0; i < 5; i++) myints.push(i);std::cout << "1. size: " << myints.size() << '\n';myints.pop();std::cout << "2. size: " << myints.size() << '\n';
}{ // std::priority_queue::top: Returns a constant reference to the top element in the priority_queue.// The top element is the element that compares higher in the priority_queue,// and the next that is removed from the container when priority_queue::pop is called.std::priority_queue<int> mypq;mypq.push(10);mypq.push(20);mypq.push(15);std::cout << "mypq.top() is now " << mypq.top() << '\n';
}{ // std::priority_queue::swap: C++11, Exchanges the contents of the container adaptor by those of x,// swapping both the underlying container value and their comparison function using// the corresponding swap non-member functions (unqualified)// std::swap (priority_queue): Exchange contents of priority queuesstd::priority_queue<int> foo, bar;foo.push(15); foo.push(30); foo.push(10);bar.push(101); bar.push(202);foo.swap(bar);//std::swap(foo, bar);std::cout << "size of foo: " << foo.size() << '\n';std::cout << "size of bar: " << bar.size() << '\n';
}return 0;
}//
// reference: http://en.cppreference.com/w/cpp/container/priority_queue
template<typename T>
static void print_queue(T& q) {while (!q.empty()) {std::cout << q.top() << " ";q.pop();}std::cout << '\n';
}int test_priority_queue_2()
{std::priority_queue<int> q;for (int n : {1, 8, 5, 6, 3, 4, 0, 9, 7, 2})q.push(n);print_queue(q);std::priority_queue<int, std::vector<int>, std::greater<int> > q2;for (int n : {1, 8, 5, 6, 3, 4, 0, 9, 7, 2})q2.push(n);print_queue(q2);// Using lambda to compare elements.auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1); };std::priority_queue<int, std::vector<int>, decltype(cmp)> q3(cmp);for (int n : {1, 8, 5, 6, 3, 4, 0, 9, 7, 2})q3.push(n);print_queue(q3);return 0;
}/
// reference: http://www.technical-recipes.com/2011/priority-queues-and-min-priority-queues-in-c/
struct compare {bool operator()(const int& l, const int& r) {return l > r;}
};int test_priority_queue_3()
{using namespace std;priority_queue<int, vector<int>, compare > pq;pq.push(3);pq.push(5);pq.push(1);pq.push(8);std::cout << "pq contains:";while (!pq.empty()) {std::cout << ' ' << pq.top();pq.pop();}std::cout << '\n';return 0;
}/
// reference: https://msdn.microsoft.com/en-us/library/4ef4dae9.aspx
int test_priority_queue_4()
{
{ // priority_queue::container_type: A type that provides the base container to be adapted.// priority_queue::empty: Tests if a priority_queue is empty.// true if the priority_queue is empty; false if the priority_queue is nonempty.using namespace std;// Declares priority_queues with default deque base containerpriority_queue <int> q1, s2;q1.push(1);if (q1.empty()) cout << "The priority_queue q1 is empty." << endl;else cout << "The priority_queue q1 is not empty." << endl;if (s2.empty()) cout << "The priority_queue s2 is empty." << endl;else cout << "The priority_queue s2 is not empty." << endl;
}{ // priority_queue::pop: Removes the largest element of the priority_queue from the top position.using namespace std;priority_queue <int> q1, s2;q1.push(10);q1.push(5);q1.push(30);priority_queue <int>::size_type i, iii;i = q1.size();cout << "The priority_queue length is " << i << "." << endl;const int& ii = q1.top();cout << "The element at the top of the priority_queue is " << ii << "." << endl;q1.pop();iii = q1.size();cout << "After a pop, the priority_queue length is " << iii << "." << endl;const int& iv = q1.top();cout << "After a pop, the element at the top of the " << "priority_queue is " << iv << "." << endl;
}{ // priority_queue::priority_queue: Constructs a priority_queue that is empty or// that is a copy of a range of a base container object or of another priority_queueusing namespace std;// The first member function declares priority_queue// with a default vector base containerpriority_queue <int> q1;cout << "q1 = ( ";while (!q1.empty()) {cout << q1.top() << " ";q1.pop();}cout << ")" << endl;// Explicitly declares a priority_queue with nondefault// deque base containerpriority_queue <int, deque <int> > q2;q2.push(5);q2.push(15);q2.push(10);cout << "q2 = ( ";while (!q2.empty()) {cout << q2.top() << " ";q2.pop();}cout << ")" << endl;// This method of printing out the elements of a priority_queue// removes the elements from the priority queue, leaving it emptycout << "After printing, q2 has " << q2.size() << " elements." << endl;// The third member function declares a priority_queue// with a vector base container and specifies that the comparison// function greater is to be used for ordering elementspriority_queue <int, vector<int>, greater<int> > q3;q3.push(2);q3.push(1);q3.push(3);cout << "q3 = ( ";while (!q3.empty()) {cout << q3.top() << " ";q3.pop();}cout << ")" << endl;// The fourth member function declares a priority_queue and// initializes it with elements copied from another container:// first, inserting elements into q1, then copying q1 elements into q4q1.push(100);q1.push(200);q1.push(5);priority_queue <int> q4(q1);cout << "q4 = ( ";while (!q4.empty()) {cout << q4.top() << " ";q4.pop();}cout << ")" << endl;// Creates an auxiliary vector object v5 to be used to initialize q5vector <int> v5;vector <int>::iterator v5_Iter;v5.push_back(10);v5.push_back(30);v5.push_back(20);cout << "v5 = ( ";for (v5_Iter = v5.begin(); v5_Iter != v5.end(); v5_Iter++)cout << *v5_Iter << " ";cout << ")" << endl;// The fifth member function declares and// initializes a priority_queue q5 by copying the// range v5[ first, last) from vector v5 priority_queue <int> q5(v5.begin(), v5.begin() + 2);cout << "q5 = ( ";while (!q5.empty()) {cout << q5.top() << " ";q5.pop();}cout << ")" << endl;// The sixth member function declares a priority_queue q6// with a comparison function greater and initializes q6// by copying the range v5[ first, last) from vector v5priority_queue <int, vector<int>, greater<int> >q6(v5.begin(), v5.begin() + 2);cout << "q6 = ( ";while (!q6.empty()) {cout << q6.top() << " ";q6.pop();}cout << ")" << endl;
}{ // priority_queue::push: Adds an element to the priority queue based on the priority of the element from operator<.using namespace std;priority_queue<int> q1;q1.push(10);q1.push(30);q1.push(20);priority_queue<int>::size_type i;i = q1.size();cout << "The priority_queue length is " << i << "." << endl;const int& ii = q1.top();cout << "The element at the top of the priority_queue is " << ii << "." << endl;
}{ // priority_queue::size: Returns the number of elements in the priority_queue.// priority_queue::size_type: An unsigned integer type that can represent the number of elements in a priority_queue.using namespace std;priority_queue <int> q1, q2;priority_queue <int>::size_type i;q1.push(1);i = q1.size();cout << "The priority_queue length is " << i << "." << endl;q1.push(2);i = q1.size();cout << "The priority_queue length is now " << i << "." << endl;
}{ // priority_queue::top: Returns a const reference to the largest element at the top of the priority_queue.using namespace std;priority_queue<int> q1;q1.push(10);q1.push(30);q1.push(20);priority_queue<int>::size_type i;i = q1.size();cout << "The priority_queue length is " << i << "." << endl;const int& ii = q1.top();cout << "The element at the top of the priority_queue is " << ii << "." << endl;
}{ // priority_queue::value_type: A type that represents the type of object stored as an element in a priority_queue.using namespace std;// Declares priority_queues with default deque base containerpriority_queue<int>::value_type AnInt;AnInt = 69;cout << "The value_type is AnInt = " << AnInt << endl;priority_queue<int> q1;q1.push(AnInt);cout << "The element at the top of the priority_queue is " << q1.top() << "." << endl;
}return 0;
}
GitHub: https://github.com/fengbingchun/Messy_Test
相关文章:

left join 和 left outer join 的区别
老是混淆,做个笔记,转自:https://www.cnblogs.com/xieqian111/p/5735977.html left join 和 left outer join 的区别 通俗的讲: A left join B 的连接的记录数与A表的记录数同 A right join B 的连接的记录数与…

php减少损耗的方法之一 缓存对象
即把实例后的对象缓存起来(存入变量),当需要再次实例化时,先去缓存里查看是否存在。存在则返回。否则实例化。转载于:https://www.cnblogs.com/zuoxiaobing/p/3581139.html
windows10 vs2013控制台工程中添加并编译cuda8.0文件操作步骤
一般有两种方法可以在vs2013上添加运行cuda8.0程序:一、直接新建一个基于CUDA8.0的项目:如下图所示,点击确定后即可生成test_cuda项目;默认会自动生成一个kernel.cu文件;默认已经配置好Debug/Release, Win32/x64环境&a…

算法人必懂的进阶SQL知识,4道面试常考题
(图片付费下载自视觉中国)作者 | 石晓文来源|小小挖掘机(ID:wAlsjwj)近期在不同群里有小伙伴们提出了一些在面试和笔试中遇到的Hive SQL问题,Hive作为算法工程师的一项必备技能,在面…

007-迅雷定时重启AutoHotkey脚本-20190411
;; 定时重启迅雷.ahk,;;~ 2019年04月11日;#SingleInstance,forceSetWorkingDir,%A_ScriptDir%DetectHiddenWindows,OnSetTitleMatchMode,2#Persistent ;让脚本持久运行(即直到用户关闭或遇到 ExitApp)。#NoEnv;~ #NoTrayIcon Hotkey,^F10,ExitThisApp lo…

关于ExtJS在使用下拉列表框的二级联动获取数据
2019独角兽企业重金招聘Python工程师标准>>> 使用下拉列表框的二级联动获取数据,如果第一个下拉列表框有默认值时,需要设置fireEvent执行select事件 示例: var combo Ext.getCmp("modifyBuildCom"); combo.setValue(re…

C++中std::sort/std::stable_sort/std::partial_sort的区别及使用
某些算法会重排容器中元素的顺序,如std::sort。调用sort会重排输入序列中的元素,使之有序,它默认是利用元素类型的<运算符来实现排序的。也可以重载sort的默认排序,即通过sort的第三个参数,此参数是一个谓词(predic…

阿里云智能 AIoT 首席科学家丁险峰:阿里全面进军IoT这一年 | 问底中国IT技术演进...
作者 | 屠敏受访者 | 丁险峰来源 | CSDN(ID:CSDNnews)「忽如一夜春风来,千树万树梨花开。」从概念的流行、至科技巨头的相继入局、再到诸多应用的落地,IoT 的发展终于在万事俱备只欠东风的条件下真正地迎来了属于自己的…

eBCC性能分析最佳实践(1) - 线上lstat, vfs_fstatat 开销高情景分析...
Guide: eBCC性能分析最佳实践(0) - 开启性能分析新篇章eBCC性能分析最佳实践(1) - 线上lstat, vfs_fstatat 开销高情景分析eBCC性能分析最佳实践(2) - 一个简单的eBCC分析网络函数的latency敬请期待...0. I…

spring-data-mongodb必须了解的操作
http://docs.spring.io/spring-data/data-mongo/docs/1.0.0.M5/api/org/springframework/data/mongodb/core/MongoTemplate.html 在线api文档 1关键之识别 KeywordSampleLogical resultGreaterThanfindByAgeGreaterThan(int age){"age" : {"$gt" : age}}Le…

旷视张祥雨:高效轻量级深度模型的研究和实践 | AI ProCon 2019
演讲嘉宾 | 张祥雨(旷视研究院主任研究员、基础模型组负责人)编辑 | Just出品 | AI科技大本营(ID:rgznai100)基础模型是现代视觉识别系统中一个至关重要的关注点。基础模型的优劣主要从精度、速度或功耗等角度判定,如何…

Python脱产8期 Day02
一 语言分类 机器语言,汇编语言,高级语言(编译和解释) 二 环境变量 1、配置环境变量不是必须的2、配置环境变量的目的:为终端提供执行环境 三Python代码执行的方式 1交互式:.控制台直接编写运行python代码 …
分别用Eigen和C++(OpenCV)实现图像(矩阵)转置
(1)、标量(scalar):一个标量就是一个单独的数。(2)、向量(vector):一个向量是一列数,这些数是有序排列的,通过次序中的索引,可以确定每个单独的数。(3)、矩阵(matrix):矩阵是一个二维数组,其中的…

Linux基础优化
***************************************************************************************linux系统的优化有很多,我简单阐述下我经常优化的方针:记忆口诀:***********************一清、一精、一增;两优、四设、七其他。*****…
数据集cifar10到Caffe支持的lmdb/leveldb转换的实现
在 http://blog.csdn.net/fengbingchun/article/details/53560637 对数据集cifar10进行过介绍,它是一个普通的物体识别数据集。为了使用Caffe对cifar10数据集进行train,下面实现了将cifar10到lmdb/leveldb的转换实现:#include "funset.h…

计算两个时间的间隔时间是多少
/*** 计算两个时间间隔* param startTime 开始时间* param endTime 结束时间* param type 类型(1:相隔小时 2:)* return*/public static int compareTime(String startTime, String endTime, int type) {if (endTime nul…

作为西二旗程序员,我是这样学习的.........
作为一名合格的程序员,需要时刻保持对新技术的敏感度,并且要定期更新自己的技能储备,是每个技术人的日常必修课。但要做到这一点,知乎上的网友说最高效的办法竟然是直接跟 BAT 等一线大厂取经。讲真的,BAT大厂的平台是…

2月国内搜索市场:360继续上升 百度下降0.62%
IDC评述网(idcps.com)03月06日报道:根据CNZZ数据显示,在国内搜索引擎市场中,百度在2014年2月份所占的份额继续被蚕食,环比1月份,下降了0.62%,为60.50%。与此相反,360搜索…

不止于刷榜,三大CV赛事夺冠算法技术的“研”与“用”
(由AI科技大本营付费下载自视觉中国)整理 | Jane出品 | AI科技大本营(ID:rgznai100)在 5 个月时间里(5月-9月),创新工场旗下人工智能企业创新奇智连续在世界顶级人脸检测竞赛 WIDER …
Ubuntu14.04上编译指定版本的protobuf源码操作步骤
Google Protobuf的介绍可以参考 http://blog.csdn.net/fengbingchun/article/details/49977903 ,这里介绍在Ubuntu14.04上编译安装指定版本的protobuf的操作步骤,这里以2.4.1为例:1. Ubuntu14.04上默认安装的是2.5.0,…

Linux下,各种解压缩命令集合
Linux下,各种解压缩命令集合tar xvfj lichuanhua.tar.bz2tar xvfz lichuanhua.tar.gztar xvfz lichuanhua.tgztar xvf lichuanhua.tarunzip lichuanhua.zip.gz解压 1:gunzip FileName.gz解压 2:gzip -d FileName.gz压缩:gzip File…
gtest使用初级指南
之前在 http://blog.csdn.net/fengbingchun/article/details/39667571 中对google的开源库gtest进行过介绍,现在看那篇博文,感觉有些没有说清楚,这里再进行总结下:Google Test是Google的开源C单元测试框架,简称gtest。…

iOS视频流采集概述(AVCaptureSession)
需求:需要采集到视频帧数据从而可以进行一系列处理(如: 裁剪,旋转,美颜,特效....). 所以,必须采集到视频帧数据. 阅读前提: 使用AVFoundation框架采集音视频帧数据GitHub地址(附代码) : iOS视频流采集概述 简书地址 : iOS视频流采…

300秒搞定第一超算1万年的计算量,量子霸权时代已来?
(由AI科技大本营付费下载自视觉中国)作者 | 马超责编 | 郭芮来源 | CSDN 博客近日,美国航天局(NASA)发布了一篇名为《Quantum Supremacy Using a Programmable Superconducting Processor》的报道,称谷歌的…

2014-3-6 星期四 [第一天执行分析]
昨日进度: [毛思想]:看测控技术量待定 --> [良]超额完成,昨天基本上把测控看了一大半啦 [汇编]:认真听课,边听边消化自学 --> [中]基本满足,还需要抽时间总结,特别是前面寻址的各种情况…
行列式介绍及Eigen/OpenCV/C++的三种实现
行列式,记作det(A),是一个将方阵A映射到实数的函数。行列式等于矩阵特征值的乘积。行列式的绝对值可以用来衡量矩阵参与矩阵乘法后空间扩大或者缩小了多少。如果行列式是0,那么空间至少沿着某一维完全收缩了,使其失去了所有的体积…

基于Go的语义解析开源库FMR,“屠榜”模型外的NLP利器
(由AI科技大本营付费下载自视觉中国)作者 | 刘占亮 一览群智技术副总裁编辑 | Jane出品 | AI科技大本营(ID:rgznai100)如何合理地表示语言的内在意义?这是自然语言处理业界中长久以来悬而未决的一个命题。在…

【高级数据类型2】- 10. 接口
2019独角兽企业重金招聘Python工程师标准>>> Go语言-接口 在Go语言中,一个接口类型总是代表着某一种类型(即所有实现它的类型)的行为。一个接口类型的声明通常会包含关键字type、类型名称、关键字interface以及由花括号包裹的若干…

Linux软件包命令
2019独角兽企业重金招聘Python工程师标准>>> dpkg命令: dpkg -i **/**.deb 安装软件 dpkg -x **.deb 解开.deb文件 dpkg -r /-p 删除并清配置 更详细的 用dpkg --help 查询 如下: dpkg -i|--install <.deb 文件的文件名> ... | -R|--re…
Caffe中计算图像均值的实现(cifar10)
在深度学习中,在进行test时经常会减去train数据集的图像均值,这样做的好处是:属于数据预处理中的数据归一化,降低数据间相似性,可以将数值调整到一个合理的范围。以下code是用于计算cifar10中训练集的图像均值…