[C/C++标准库]_[初级]_[优先队列priority_queue的使用]
2014-05-04 00:20
676 查看
std::priority_queue
场景:1. 对于一个任务队列,任务的优先级由任务的priority属性指明,这时候就需要优先级越高的先执行。而queue并没有排序功能,这时priority_queue是比较好的选择.
2 对于异步的task也是一样,在不断添加新的task时,当然希望优先级越高的先执行.
解析:
1. 如果需要把优先级最高的先pop,那么comp比较时需要返回false.
代码:
//1.Elements are popped from the "back" of the specific container, //which is known as the top of the priority queue. //2.shall return true if a is considered to go before b // in the strict weak ordering the function defines #include <stdlib.h> #include <iostream> #include <queue> #include <vector> using namespace std; class Task { public: Task(int priority):priority_(priority) { } ~Task(){} int priority_; void DoWork() { cout << "DoWork: " << (int)this << " priority: " << priority_ << endl; } }; class PriorityCompare { public: bool operator()(Task* t1,Task* t2) { return t1->priority_ > t2->priority_; } /* data */ }; int main(int argc, char const *argv[]) { PriorityCompare pc; priority_queue<Task*,std::vector<Task*>,PriorityCompare> tasks(pc); Task t1(1); Task t2(10); Task t3(3); Task t4(1); Task t5(8); Task t6(9); tasks.push(&t1); tasks.push(&t2); tasks.push(&t3); tasks.push(&t4); tasks.push(&t5); tasks.push(&t6); while(!tasks.empty()) { Task* task = tasks.top(); tasks.pop(); task->DoWork(); } return 0; }
输出:
DoWork: 2293456 priority: 1 DoWork: 2293444 priority: 1 DoWork: 2293448 priority: 3 DoWork: 2293440 priority: 8 DoWork: 2293436 priority: 9 DoWork: 2293452 priority: 10
参考: http://www.cplusplus.com/reference/queue/priority_queue/
相关文章推荐
- [C/C++标准库]_[初级]_[优先队列priority_queue的使用]
- 用C语言实现面向对象之封装
- c++ server example
- c++ client example
- C/C++编译过程理解
- c/c++宏的使用总结
- C++中static的全部用法
- C++中的typeid关键字
- 关于C++中函数指针的使用
- C++语言中const的用法
- C++函数调用过程深入分析
- <<C语言接口与实现>> 第五章 内存管理
- 在宏中使得字段只能读取 (几何画板开发笔记 三)
- C语言负数的除法和求余运算
- 水滴石穿C语言之指针综合谈
- C++程序员应聘常见面试题深入剖析
- 基于C语言的SQLite操作接口函数简介
- SQLITE3 C语言接口 API 函数简介
- 用c++封装一个Hash Table,并与STL map 进行操作性能上的比较
- C++ STL入门教程(2)——list(双向链表)的使用(附完整程序代码)