Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stl priority_queue of C++ with struct

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 ?

like image 456
Manas Verma Avatar asked Mar 24 '13 17:03

Manas Verma


1 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();
like image 54
juanchopanza Avatar answered Sep 28 '22 07:09

juanchopanza