greater in C++
时间: 2024-01-21 21:02:05 浏览: 36
In C++, "greater" is a function object that compares two values and returns true if the first value is greater than the second value. It is defined in the <functional> header file and can be used with various standard library algorithms like std::sort, std::max_element, etc.
Here's an example of using "greater" to sort a vector in descending order:
```
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
int main() {
std::vector<int> nums = {5, 2, 8, 3, 1};
// Sort in descending order using greater
std::sort(nums.begin(), nums.end(), std::greater<int>());
// Print sorted vector
for (auto num : nums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
```
Output:
```
8 5 3 2 1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)