程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [C/C++標准庫]_[優先隊列priority_queue的使用]

[C/C++標准庫]_[優先隊列priority_queue的使用]

編輯:C++入門知識


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 
#include 
#include 
#include 
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,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/


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved