Container Adaptors

Its OK to figure out murder mysteries, but you shouldn't need to figure out code. You should be able to read it. Steve McConnell

priority queue

Language C++ | Level Intermediate | Category Standard Template Library (STL) | 2015-11-16 22:47:37

0 Comments


Definition

Priority queue is a container which store and remove the items based on the priority. Priority queue does not allow the iteration trough the elements. It look up the largest item in constant time.

Character

The largest element is always at the top position.
It always remove the high priority items.
Peek returns the highest-priority element.
Common implementations are circular buffers and linked lists. Priority queues are often implemented with heaps.
Priority queue is a queue with priority information associated with queue.

source Code

								
#include "stdafx.h"

#include < iostream > 
#include < queue >     
#include < vector >   
#include < functional >
using namespace std;

class Employee {
public:
	string ename;
	int nage;
	Employee() : ename(""), nage(0)
	{
	
	}
	Employee(string name, int age)
	{
		ename = name;
		nage = age;
	}

	bool operator()(Employee const & e1, Employee const & e2) {
		return e1.nage < e2.nage;
	}

};

bool operator > (const Employee& structstudent1, const Employee &structstudent2)
{
	return structstudent1.nage > structstudent2.nage;
}

int _tmain(int argc, _TCHAR* argv[])
{
	priority_queue < Employee, vector < Employee >, greater < vector < Employee >::value_type > > employee;
	
	cout << "Store employee details to priority queue : 'siva', 'Tim','Mark'" << endl;
	employee.push(Employee("siva", 38));
	employee.push(Employee("Tim", 47));
	employee.push(Employee("Mark", 25));
	

	cout << "Display employee details from priority queue : " << endl;
	while (!employee.empty()) {
		cout << employee.top().ename.c_str() << endl;
		employee.pop();
	}
	cout << endl;

	return 0;
}

						

Output

    					 
					Store employee details to priority queue : 'siva', 'Tim','Mark'
					Display employee details from priority queue :
					Mark
					siva
					Tim
					    					 
					    

When to use

When you want maintain the priority with first in first out order. You can use Priority queue.

0 Comments



Please login to add comments.