https://cn.bing.com/search?pglt=417&q=greater%3Cstring%3E
std::sort(numbers, numbers + 5, std::greater<int>());,std::greater{}也可以
#if _LIBCPP_STD_VER >= 14 template <class _Tp = void> #else template <class _Tp> #endif struct _LIBCPP_TEMPLATE_VIS greater : __binary_function<_Tp, _Tp, bool> { typedef bool __result_type; // used by valarray _LIBCPP_CONSTEXPR_SINCE_CXX14 _LIBCPP_HIDE_FROM_ABI bool operator()(const _Tp& __x, const _Tp& __y) const { return __x > __y; } }; _LIBCPP_CTAD_SUPPORTED_FOR_TYPE(greater);std::greater in C++
The std::greater is a function object class template in C++ that performs a greater-than comparison between two values. It is defined in the header and is part of the C++ Standard Library. This function object returns true if the first argument is greater than the second argument, and false otherwise.
Definition and Usage
The std::greater template is defined as follows:
#include <functional> template <class T> struct greater { bool operator()(const T& x, const T& y) const { return x > y; } };This template can be used to create objects that can be called with the same syntax as a function call. The operator() member function performs the comparison using the > operator.
Example
Here is an example of how to use std::greater with the std::sort algorithm to sort an array in descending order:
#include <iostream> #include <functional> #include <algorithm> int main() { int numbers[] = {20, 40, 50, 10, 30}; std::sort(numbers, numbers + 5, std::greater<int>()); for (int i = 0; i < 5; i++) std::cout << numbers[i] << ' '; std::cout << '\n'; return 0; }Output: 50 40 30 20 10
In this example, std::greater() is used as the comparison function for std::sort, which sorts the array in descending order.
Practical Applications
The std::greater function object is useful in various standard algorithms such as std::sort, std::merge, and std::lower_bound where a greater-than comparison is needed. It provides a convenient and readable way to specify custom comparison logic without having to define separate comparison functions.
Important Considerations
Template Parameter: The type T must support the > operator for std::greater to work correctly.
Member Types: The std::greater template defines member types such as first_argument_type, second_argument_type, and result_type, which are deprecated in C++17 and removed in C++20.
By using std::greater, you can easily implement greater-than comparisons in your C++ programs, making your code more concise and expressive.