#include <iostream>
#include <vector>
#include <algorithm> // 包含sort函数
using namespace std;
int main() {
// 定义一个整数向量
vector<int> nums = {5, 2, 9, 1, 5, 6};
// 使用sort函数对向量进行排序,默认升序
sort(nums.begin(), nums.end());
// 输出排序后的结果
cout << "Sorted array in ascending order: ";
for (int num : nums) {
cout << num << " ";
}
cout << endl;
// 定义一个降序排序的比较函数
auto compare = [](int a, int b) {
return a > b;
};
// 使用sort函数对向量进行降序排序
sort(nums.begin(), nums.end(), compare);
// 输出降序排序后的结果
cout << "Sorted array in descending order: ";
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
#include <algorithm> 是为了使用 sort 函数。std::vector<int> 来存储一组整数。sort(nums.begin(), nums.end()) 对向量进行升序排序。compare,并在 sort 函数中传入该比较函数以实现降序排序。这个示例展示了如何在 C++ 中使用 sort 函数对数组或容器进行排序,并且可以指定排序顺序。
上一篇:c++随机数生成代码
下一篇:c++字符串类型
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站