std::p riority_queue
Scene:
1. For a task queue, the priority of the task is indicated by the task's precedence attribute, which requires a higher priority to run first. The queue does not have a sorting function, and priority_queue is a better choice.
2 The same is true for asynchronous tasks. As you continue to add new tasks, of course, you want the higher priority to run first.
Analytical:
1. If you need to prioritize the first POPs, then comp will need to return false.
Code:
1.Elements was popped from the ' back ' of the specific container,//which is known as the top of the ' the priority ' QUEUE.//2.S Hall 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):p Riority_ (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;}
Output:
dowork:2293456 priority:1dowork:2293444 priority:1dowork:2293448 priority:3dowork:2293440 priority:8dowork:229343 6 priority:9dowork:2293452 Priority:10
References: http://www.cplusplus.com/reference/queue/priority_queue/
[Use of]_[0 base]_[priority Queue Priority_queue]