Stl priority_queue from C ++ with structure

How can we use STL priority_queue for struct? Any illustrations of pushing and popping where the struct has multiple data types?
Say: struct thing { int a; char b;} glass[10]; struct thing { int a; char b;} glass[10]; .
Now how can I put this structure in priority_queue using 'int a' for ordering?

+6
source share
3 answers

Here is a slightly modified answer to your original question that you deleted for no apparent reason. The original contains enough information for you to understand this, but here it goes: let's get smaller than the comparison, which int uses for comparison.

All you have to do is provide a functor that implements less than a strict weak order comparison, or less than an operator for your class that implements it. This structure meets the requirements of:

 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(); 
+13
source

Overload operator < for thing :

 struct thing { int a; char b; bool operator<(const thing &o) const { return a < oa; } }; priority_queue<thing> pq; thing t1, t2, t3; // ... pq.push(t1); pq.push(t2); // ... t3 = pq.top(); pq.pop(); 
+4
source

You need to implement a comparison function or an overload operator to indicate the priority queue in which order you want to sort your user data. When the priority queue will sort your data, then you will need a way to find out how to compare them. You must specify this by passing the function to the priority queue or the overload operator in your custom data class or structure.

You can check this answer. It can help you. I tried to explain several ways to use the priority queue for custom data types.

+2
source

All Articles