2

When I am writing code, I was confused by the usage of the functor.

If I want to sort a sequence of integers in descending order, I have to put greater<int> in the third parameter of sort, e.g. sort(v.begin(), v.end(), greater<int>());.

But when dealing with priority_queue, I have to put less<int> in the third parameter to get a maximum-top-heap, e.g. priority_queue< int, vector <int>, less<int> > heap;.

So My question is that why we get the same ascending relation using two different functor?

Could anyone explain why this is happening? Better use the source code from the implement of STL to make me clear.

Apologize for my poor English.

Thanks a lot!

3
  • 1
    We'll explain your question the moment you ask something. What exactly isn't clear? Commented Sep 1, 2013 at 10:02
  • ascending order with std::greater<int> ? I think you mean descending order ? If that's the case your question won't make sense Commented Sep 1, 2013 at 10:10
  • Yeah, I mean descending order with std::greater<int> in STL sort,and I wrote it clearly. Commented Sep 1, 2013 at 15:03

1 Answer 1

5

The default sort sorts in ascending order, using "less-than" as the strict weak ordering for comparing elements. The default priority_queue guarantees that the top element is the largest one (i.e. it "sorts" in descending order), again using "less-than" as the strict weak ordering for comparing elements. If you want to reverse the semantics, in both cases, you can use "greater" instead of the default "less-than", as the strict weak ordering.

Sign up to request clarification or add additional context in comments.

2 Comments

So you mean the functor does not really denote the relation, it changes the default relation into another different way?
The functor denotes the relation indeed. It's just the semantics of the two things (sort vs. priority_queue) which are inverse. The former sorts in ascending order (given your relation) whereas the latter keeps "sorted" in descending order (again, given your relation).