简体   繁体   中英

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?

eg

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));

You can compare it by second element using std::get :

int main()
{
    auto cmp = [](const std::tuple<int,int>& left, const std::tuple<int,int>& right)
        {
            return std::get<1>(left) > std::get<1>(right);
        };
    std::priority_queue<std::tuple<int,int>, std::vector<std::tuple<int,int>>, decltype(cmp)> pq(cmp);
    pq.push(std::make_tuple(3,2));
    pq.push(std::make_tuple(4,9));
    pq.push(std::make_tuple(1,5));
    while (pq.empty() == false)
    {
        std::cout << std::get<1>(pq.top()) << std::endl;
        pq.pop();
    }
    return 0;
}

expected output:

2
5
9

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM