简体   繁体   中英

Create priority_queue with pair such that sorting is “<” for first element and “>” for second element when 1st elements are equal

I have a basic doubt, in that I am trying to figure out the versatility of priority_queue STL in C++.

I know that priority queue by default is actually a max_heap. I also am aware that it can be modified in the following way to create a min_heap:

priority_queue <int, vector<int>, greater<int> > pq;

What I aim to achieve, is that I want to create a priority_queue <pair <int,int> pq , such that heap is a max_heap for the first element in the pair, and it is a min_heap for the second element in the pair. For example, on inserting the following pairs:

(2,4) (1,5) (1,6)

The output when elements are displayed is as follows:

(2,4)
(1,5)
(1,6)

By default, the output would have been:

(2,4)
(1,6)
(1,5)

Is it possible? If yes, then how?

Thank you in advance.

You can write a custom comparison that compares the first element with operator< , and the second element with operator> .

struct less_then_greater {
    template<typename T, typename U>
    bool operator()(T const& lhs, U const& rhs) const {
        if (lhs.first < rhs.first) return true;
        if (rhs.first < lhs.first) return false;
        return lhs.second > lhs.second;
    }
};

std::priority_queue<std::pair<int, int>,
                    std::vector<std::pair<int, int>>,
                    less_then_greater
                   > pq;

Note that this isn't creating a min-heap for one, and a max-heap for the other. But based on the output you describe, I don't think that's what you were really asking for.

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