Reputation: 14695
The recommended way (eg: Sorting a vector in descending order) of sorting a container in reverse seems to be:
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
I understand the third argument is a function or a functor that helps sort() make the comparisons, and that std::greater is a template functor, but I don't understand what's going on here. My C++ is quite rusty so please bear with me if these are stupid questions: Why are there parentheses after std::greater<int>
there? Are we creating a new std::greater
object here? In that case, why don't we need the new
keyword here?
Upvotes: 5
Views: 948
Reputation: 8896
Why are there parentheses after std::greater there? Are we creating a new std::greater object here?
That's correct. The expression std::greater<int>()
corresponds to creating an object of type std::greater<int>
.
In that case, why don't we need the new keyword here?
We don't need the new
keyword because the object is being created on the stack, rather than on the heap. Only objects created dynamically need to be on the heap. The difference is clearly explained here.
Basically, at compile time, the compiler already knows how much memory to allocate for the object, as well as when it should be destroyed (which is when the std::sort function goes out of scope). new
should be used whenever
Upvotes: 7