#include <iostream>
#include <vector>
#include <algorithm> // 包含sort函数的头文件
using namespace std;
int main() {
vector<int> nums = {5, 2, 9, 1, 5, 6};
// 使用sort函数对vector进行排序,默认是升序排序
sort(nums.begin(), nums.end());
// 输出排序后的结果
cout << "Sorted numbers: ";
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
#include <algorithm>
:引入了C++标准库中的algorithm
头文件,该文件包含了sort
函数。vector<int> nums = {5, 2, 9, 1, 5, 6};
:定义了一个包含整数的vector
,并初始化了一些值。sort(nums.begin(), nums.end());
:调用sort
函数对nums
中的元素进行排序。begin()
和end()
分别返回指向vector
首尾的迭代器,表示要排序的范围。for (int num : nums)
:使用范围for
循环遍历并输出排序后的结果。这段代码展示了如何使用C++中的sort
函数对一个整数数组进行排序。
下一篇:c++ 打开文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站