[Use of]_[0 base]_[priority Queue Priority_queue]

Source: Internet
Author: User


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 (&AMP;T1); Tasks.push (&AMP;T2); Tasks.push (&AMP;T3); Tasks.push (&AMP;T4); Tasks.push (&AMP;T5); Tasks.push (&AMP;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]

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.