Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pair inside priority queue

I am trying to store pairs in priority queue and I am using a compare function that compares second value of each pair.

#include<iostream> #include<queue> #include<utility> using namespace std;  class CompareDist { public:     bool operator()(pair<int,int> n1,pair<int,int> n2) {         return n1.second>n2.second;     } }; int main() {     priority_queue<pair<int,int>,CompareDist> pq; } 

When I compile this I get an error

error: no type named ‘value_type’ in ‘class CompareDist’ 

What could be the reason.I am new to STL.

like image 693
g4ur4v Avatar asked Oct 02 '12 07:10

g4ur4v


People also ask

Can we use pair in priority queue?

Priority Queue ordered by first element In C++ if the element is in the form of pairs, then by default the priority of the elements is dependent upon the first element. Therefore, we just have to use the priority queue of pairs only.

How pair is stored in priority queue?

Priority queue is an abstract data type for storing a collection of prioritized elements that supports insertion and deletion of an element based upon their priorities, that is, the element with first priority can be removed at any time.

What happens if two elements have the same priority in priority queue?

In a priority queue, an element with high priority is served before an element with low priority. In some implementations, if two elements have the same priority, they are served according to the order in which they were enqueued; in other implementations ordering of elements with the same priority remains undefined.


2 Answers

This is what priority_queue looks like:

template<     class T,     class Container = std::vector<T>,      class Compare = std::less<typename Container::value_type> > class priority_queue; 

In other words, CompareDist should be the third argument and the second argument should be the container (which has value_type), like the following:

priority_queue<pair<int,int>,vector<pair<int,int>>,CompareDist> pq; 

Notice also, that priority_queue is what is called a "container adaptor". Another container is used as the underlying container and the priority_queue has special members functions for accessing it. Another example of a container adaptor would be std::stack.

like image 134
Jesse Good Avatar answered Oct 20 '22 14:10

Jesse Good


priority_queue<pair<int,int>,vector<pair<int,int>>,CompareDist> pq; 

you need to provide second argument for the inbuilt template of priority_queue.

like image 37
RAMENDRA SINGH Avatar answered Oct 20 '22 15:10

RAMENDRA SINGH