C++STL之priority_queue优先队列容器
2015-10-23 12:39
781 查看
特征:就是队列中最大元素总是在队首
*优先队列使用方法
*重载"<"操作符来定义优先级
如果优先队列的元素类型是结构体,可以通过在结构体中重载"<"操作符的方法来修改优先队列的优先性。
*重载“()”操作符来定义优先级
如果优先队列元素不是结构体类型,可以通过重载"()"操作符的方式来定义优先级,当然若元素是结构体类型,也可以通过重载"()"操作符的方式来定义优先级,而不是一定要在结构体内重载"<"操作符。
*优先队列使用方法
#include<iostream> #include<queue> using namespace std; int main() { priority_queue<int> pq; pq.push(2); pq.push(0); pq.push(1); pq.push(5); cout<<pq.size()<<endl; while(pq.empty() != true) { cout<<pq.top()<<" "; pq.pop(); } cout<<endl; return 0; }
*重载"<"操作符来定义优先级
如果优先队列的元素类型是结构体,可以通过在结构体中重载"<"操作符的方法来修改优先队列的优先性。
#include<iostream> #include<string> #include<queue> using namespace std; struct Info { string name; float score; bool operator < (const Info& a)const { //由小到大排序 return a.score < score; } }; int main() { priority_queue<Info> pq; Info info; info.name = "CaiCai"; info.score = 68.5; pq.push(info); info.name = "Zhejiang"; info.score = 90; pq.push(info); info.name = "Ningbo"; info.score = 78.2; pq.push(info); while(pq.empty() != true) { cout<<pq.top().name<<" : "<<pq.top().score<<endl; pq.pop(); } return 0; }
*重载“()”操作符来定义优先级
如果优先队列元素不是结构体类型,可以通过重载"()"操作符的方式来定义优先级,当然若元素是结构体类型,也可以通过重载"()"操作符的方式来定义优先级,而不是一定要在结构体内重载"<"操作符。
#include<iostream> #include<vector> #include<queue> using namespace std; struct cmp { bool operator () (const int& a, const int& b) { //由小到大 return a < b; } }; int main() { priority_queue<int, vector<int>, cmp> pq; pq.push(2); pq.push(0); pq.push(1); pq.push(5); pq.push(10); pq.push(23); while(pq.empty() != true) { cout<<pq.top()<<" "; pq.pop(); } cout<<endl; return 0; }
相关文章推荐
- C++——将成员函数作为参数
- Leetcode Next Permutation
- c++ de-mangle 反编译器命名工具:c++filt
- C++笔试题 字符串的比较,全排列,类似 和分解的问题
- 所用的软件是visualc++6.0绿色版,点击运行后出现[local]1[/local]
- c语言学习之基础知识点介绍(五):关系运算式和逻辑运算式
- 微软承诺将在今年的 Visual C++ 更新中加入 Clang 编译器
- LoadRunner 常用C语言函数使用
- c++, windows系统 复制粘贴 任意字符名称 文件
- 1028. 人口普查(20)
- c++问题之-- MessageBoxW”: 不能将参数 2 从“char [20]”转换为“LPCWSTR”
- C++-----------------------------------------------------std::bind
- memmove与memcpy区别
- configure: error: C++ preprocessor "/lib/cpp" fails sanity check
- c++问题之--This function or variable may be unsafe. Consider using sprintf_s instead
- c语言中的函数的定义以及相关的调用、嵌套、递归以及和数组的关系
- C++项目编译后生成哪些文件?
- C++好书列表
- 浅谈C++多态性
- C++线程池的实现(二)