简体   繁体   中英

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

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?

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, ie you want the object to outlast the lifetime of the scope where it was created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM