Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++sort函数

作者:烟寂断魂   发布日期:2025-11-24   浏览:98

#include <iostream>
#include <vector>
#include <algorithm> // 包含sort函数

using namespace std;

int main() {
    // 创建一个整数向量
    vector<int> numbers = {5, 2, 9, 1, 5, 6};

    // 使用sort函数对向量进行排序
    sort(numbers.begin(), numbers.end());

    // 输出排序后的结果
    cout << "Sorted numbers: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

解释说明:

  1. 包含头文件#include <algorithm> 是为了使用 std::sort 函数。
  2. 创建向量:我们创建了一个包含整数的 vector<int>,并初始化了一些数值。
  3. 调用 sort 函数sort(numbers.begin(), numbers.end())numbers 向量中的元素进行升序排序。begin()end() 分别返回向量的起始和结束迭代器。
  4. 输出结果:使用范围 for 循环遍历并输出排序后的向量元素。

如果你需要对自定义类型或使用不同的排序规则(如降序),可以传递第三个参数作为比较函数。

上一篇:switch c++

下一篇:c++友元函数

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++格式化字符串

c++ orm框架

c++ random函数用法

队列c++

c++freopen怎么用

进制转换c++代码

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站