Some people write
std::nth_element(v.begin(), v.begin()+1, v.end(), std::greater{});
and some write like this
std::nth_element(v.begin(), v.begin()+1, v.end(), std::greater<int>());
What is thre diffrence between std::greater{}
and std::greater<int>()
?
This is new as of C++14, and this results in two completely different classes.
In C++14, std::greater
acquires a default value for its template parameter: void
.
You end up with either std::greater<void>
or std::greater<int>
.
std::greater<void>
is a specialization for a so-called "transparent" comparator that deduces its parameters, see its reference for more information.
std::greater<int>
has an bool operator()(int const&,int const&) const
that calls >
.
std::greater<>
, aka std::greater<void>
, has a template references auto operator()(T const&, U const&) const
that calls >
and deduces its return value.
In c++11 and earlier, greater<void>
and <>
won't work.
In practice there will be no difference here. Under any non zero optimization, both versions of the comparison will be inlined.
In other contexts, the void
version will let you compare dissimilar types (with suitable <
or conversion overloads), and lets you neglect the type you are comparing.
The other big detail is that <void>
advertises a is_transparent
tag. When passed to a container like std::map
, it changes some of the methods to have template arguments. This permits using a std::string
key without forcing the lookup strings to become the same object type, which can save copies and allocations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With