I am curious about the use of std::greater. When used with sort, it outputs the numbers in descending order. But when used with priority_queue, numbers are output in ascending order. Why so?
Example:
#include <iostream> // std::cout #include <functional> // std::greater #include <algorithm> // std::sort #include <queue> // std::priority_queue int main () { int numbers[]={20,40,50,10,30}; std::priority_queue<int, std::vector<int>, std::greater<int>> pq (numbers, numbers+5); std::sort(numbers, numbers + 5, std::greater<int>()); while(!pq.empty()){ std:: cout << pq.top() << ' '; pq.pop(); } std::cout << '\n'; for (int i=0; i<5; i++) std::cout << numbers[i] << ' '; return 0; } The output of above code is:
10 20 30 40 50 50 40 30 20 10
Or similar lines,
std::priority_queue<int, std::vector<int>, std::greater<int> > creates a min heap whereas std::priority_queue<int, std::vector<int>, std::less<int> > creates a max heap. Could have been the other way round. Why is it so?
std::sortsorts in the opposite order ofstd::priority_queueand has nothing to do withstd::greater. Edit : This is not an explanation for the downvote, I didn't downvote.