How can we use STL priority_queue for struct ?
Any illustration of pushing & popping , where struct has multiple data-types?
Say : struct thing { int a; char b;} glass[10]; .
Now how can i put this struct on priority_queue using 'int a' for ordering ?
- 332
- 1
- 2
- 12
4 Answers
Here is a slightly modified answer to your original question, which you deleted for no apparent reason. The original contained enough information for you to figure this out, but here it goes: provide a less than comparison that uses the int for comparison.
All you need to do is provide a functor that implements a less-than comparison with strict weak ordering, or a less-than operator for your class implementing the same. This struct satisfies the requirements:
struct thing
{
int a;
char b;
bool operator<(const thing& rhs) const
{
return a < rhs.a;
}
};
then
std::priority_queue<thing> q;
thing stuff = {42, 'x'};
q.push(stuff);
q.push(thing{4242, 'y'}); // C++11 only
q.emplace(424242, 'z'); // C++11 only
thing otherStuff = q.top();
q.pop();
- 1
- 1
- 216,937
- 30
- 383
- 461
-
Thanks ^_^ & just 1 last thing : how will i push say (3,a) to the queue direclty ? i dont know how to put (3,a) to 'thing stuff= **...**' . – Manas Verma Mar 24 '13 at 18:09
-
In c++11, you can say `q.push(thing{42, 'x'})` or `q.emplace(42, 'x')`. If you don't have C++11 support, you need to give `thing` a constructor. – juanchopanza Mar 24 '13 at 18:14
-
Is it necessary for the argument to be a const reference? Why cant we simply do bool operator – Evil_Transistor Oct 14 '20 at 14:41
Overload < operator for thing :
struct thing
{
int a;
char b;
bool operator<(const thing &o) const
{
return a < o.a;
}
};
priority_queue<thing> pq;
thing t1, t2, t3;
// ...
pq.push(t1);
pq.push(t2);
// ...
t3 = pq.top();
pq.pop();
- 53,199
- 16
- 130
- 198
You need to implement a compare function or overload operator to tell priority queue that on which order you want to sort your custom data. When priority queue will sort your data then it will need a way to know how to compare among them. You have to specify this by passing a function to priority queue or overloading operator in you custom data class or structure.
You can check this answer. This might help you. I have tried to explain multiple ways of using priority queue for custom data types.
- 5,008
- 3
- 23
- 37
You can do it like this!
struct example{
int height;
int weight;
};
struct comp{
bool operator()(struct example a, struct example b){
//Sorting on the basis of height(Just for example)
return (a.height > b.height);
}
};
// And here comes your priority queue
priority_queue<struct example, vector<struct example>, comp> pq;
struct example your_obj;
pq.push(your_obj);
- 169
- 1
- 3