#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;
// 如果需要降序排序,可以传递一个比较函数
sort(nums.begin(), nums.end(), greater<int>());
// 输出降序排序后的结果
cout << "Sorted array in descending order: ";
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
#include <algorithm> 是为了使用 std::sort 函数。std::vector<int> 来存储一组整数。sort(nums.begin(), nums.end()) 对向量进行升序排序。greater<int>() 给 sort 函数,可以实现降序排序。for 循环遍历并输出排序后的结果。希望这段代码和解释对你有帮助!
上一篇:c++有指针吗
下一篇:c++vector用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站