Ashwin Baskaran Ashwin Baskaran - 6 days ago 5
C++ Question

greater/less function objects in C++

I have gone through the function object documentation for greater, less. Though I do sort of understand what is in it, I don't get it yet. Will using a greater sort my container in an ascending or descending order? I am especially confused because the following two lines seem to be doing opposite things.

std::priority_queue<int, std::vector<int>, std::greater<int> > q2;

for(int n : {1,8,5,6,3,4,0,9,7,2})
q2.push(n);

print_queue(p2);


This prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. But,

int x[10] = { 1,3,5,7,9,2,4,6,8,10 };
std::sort(x,x+10,std::greater<int>());


Printing this would give 10, 9, 8, 7, 6, 5, 4, 3, 2, 1.

It would be nice if someone could describe how 'greater' works in my examples, instead of just saying how 'greater' works in general.

Answer

It will be ascending , you'll always pop the smallest element of the queue. A priority queue sorts in reverse to the order relation it is given.

The default template definition looks like this:

template<
    class T,
    class Container = std::vector<T>,
    class Compare = std::less<typename Container::value_type>
> class priority_queue;

It applies less<>()(lhs, rhs) to get the "biggest" rhs element. But in your case, it will apply greater<>()(lhs, rhs) to get the "biggest" rhs element (which will of course be the smallest).

std::sort, on the other hand, preserves the order type you give it. So std::less will sort in ascending order, and std::greater in descending order.

Comments