[C/C ++ standard library] _ [Use of priority queue priority_queue]

Source: Internet
Author: User


Std: priority_queue

Scenario:

1. For a task queue, the priority of the task is specified by the priority attribute of the task. In this case, the task must be executed first with a higher priority. The queue does not have the sorting function. In this case, priority_queue is a good choice.

2. The same is true for asynchronous tasks. When new tasks are added continuously, execute tasks with a higher priority.


Resolution:

1. If you need to set the first pop with the highest priority, false must be returned for comp comparison.


Code:

//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;}
     
    
   
  
 

Output:

DoWork: 2293456 priority: 1DoWork: 2293444 priority: 1DoWork: 2293448 priority: 3DoWork: 2293440 priority: 8DoWork: 2293436 priority: 9DoWork: 2293452 priority: 10

Reference: http://www.cplusplus.com/reference/queue/priority_queue/


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.