dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Mar 5, 1999

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Qualifying an Element of Priority Queue

The Standard Template Library defines a specialized form of the queue<> container called priority_queue<>. A priority_queue is a queue whose elements are internally sorted according to their priority. Thus, an element with the highest priority is located at the top. To qualify as an element of priority_queue<>, an object has to define the < operator. For example:
 
#include <functional> // definition of less<> 
#include <queue>  // definition of priority_queue<>
#include <iostream>
using namespace std;

struct Task
{
  int priority;
  friend bool operator < (const Task& t1, const Task& t2);
  Task(int p=0) : priority(p) {}  
};

bool operator < (const Task& t1, const Task& t2) 
{ 
	return t1.priority < t2.priority;
}

int main()
{
  priority_queue<Task> scheduler;
  scheduler.push(Task(3));
  scheduler.push(Task(5));
  scheduler.push(Task(1));

  cout<< scheduler.top().priority <<endl;   // output 5
}
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date