Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Priority queue for user-defined types

I have the below struct

struct node{
   float val;
   int count;

}

I have several objects of this struct. Now, I want to insert these objects into a priority queue of STL such that the priority queue orders the items by count. Any idea on how to do so? Preferably a min heap is preferred. I know how to do the above for primitive data types, not structs

like image 446
Programmer Avatar asked Feb 07 '12 14:02

Programmer


People also ask

What is the default priority queue?

However in C++ STL, by default, the top element is always the greatest element. We can also change it to the smallest element at the top. Priority queues are built on the top to the max heap and uses array or vector as an internal structure.

How do you structure a priority queue?

Begin Define a structure of type student. Initialize variables in student structure. Define another structure of type comparemarks Overload the variables of student structure in comapremarks structure. Use priority queue with structure.

How is STL priority queue implemented in C++?

C++ Software Engineering The priority queue in the STL of C++ is a dynamically resizing container to implement the special case of priority queye under the queue data structure. It is a sequential linear container. The top element of the priority queue is the greatest with all elements arranged in non-increasing order.

Which container class can be used as underlying container for priority_queue?

Suitable underlying container classes for priority_queue include deque Class and the default vector Class or any other sequence container that supports the operations of front , push_back , and pop_back and a random-access iterator.


2 Answers

Overload the < operator:

bool operator<(const node& a, const node& b) {
  return a.count > b.count;
}

I have reversed the comparison to achieve min heap wihtout passing extra arguments to the priority queue. Now you use it like this:

priority_queue<node> pq;
...

Edit: take a look at this post which seems to be almost exact duplicate: STL Priority Queue on custom class

like image 81
Ivaylo Strandjev Avatar answered Sep 23 '22 07:09

Ivaylo Strandjev


#include <iostream>
#include <queue>
#include <vector>
using namespace std;
class Boxer{
    public:
        string name;
        int strength;
};
struct Comp{
    bool operator()(const Boxer& a, const Boxer& b){
        return a.strength<b.strength;
    }
};
int main(){
    Boxer boxer[3];
    boxer[0].name="uday", boxer[0].strength=23;
    boxer[1].name="manoj", boxer[1].strength=33;
    boxer[2].name="rajiv", boxer[2].strength=53;

    priority_queue< Boxer, vector<Boxer>, Comp> pq;
    pq.push(boxer[0]);
    pq.push(boxer[1]);
    pq.push(boxer[2]);
    Boxer b = pq.top();
    cout<<b.name;
    //result is Rajiv

    return 0;
}
like image 36
Uday Hiwarale Avatar answered Sep 24 '22 07:09

Uday Hiwarale