Search code examples
c++priority-queuemin-heap

How to make a min heap of tuples sorted by the 2nd element?


So I can make a min heap by doing the following:

// Creates a min heap
priority_queue <int, vector<int>, greater<int> > pq;
pq.push(5);
pq.push(1);
pq.push(10);
pq.push(30);
pq.push(20);

// One by one extract items from min heap
while (pq.empty() == false)
{
    cout << pq.top() << " ";
    pq.pop();
}

return 0;

But what if my heap is a tuple of a pair ints and I want to sort by the 2nd element?

e.g.

priority_queue<tuple<int,int>, vector<tuple<int,int>>> pq;
pq.push(make_tuple(3,2));
pq.push(make_tuple(4,9));
pq.push(make_tuple(1,5));

Solution

  • You can do this in two ways:

    1. Change the order of the tuple so the column you want to sort is the first in the tuple.

    2. Create a custom comparator outside of your function definition.

       Struct Comparator {
          bool operator()(tuple<int, int>& t1, tuple<int, int>& t2) {
               return std::get<1>(t1) > std::get<1>(t2);
           }
       }
      

    Then, you can use this comparator instead of greater<tuple<int, int>> as such:

        priority_queue<tuple<int, int>, vector<tuple<int, int>>, Comparator> pq;
    

    This comes in very handy when you're dealing with complex objects and you want to sort by a specific attribute.