Syntax for using std::greater when calling std::sort in C++

c++, std, stl

Solution

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

- this information is not available -- a simple example is when you want to create an array of objects, but you don't know how many objects, until the program actually runs; and/or

- you want objects to have persistent storage duration, i.e. you want the object to outlast the lifetime of the scope where it was created.

Problem

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?

Original source

Related problems