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

c++中sort函数用法

作者:似水韶华该惜谁ら   发布日期:2026-01-18   浏览:62

#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;
}

解释说明:

  1. 包含头文件#include <algorithm> 是为了使用 sort 函数。
  2. 定义容器:这里使用了 std::vector<int> 来存储一组整数。
  3. 默认升序排序:调用 sort(nums.begin(), nums.end()) 对向量进行升序排序。
  4. 自定义比较函数:通过 lambda 表达式定义了一个降序排序的比较函数 compare,并在 sort 函数中传入该比较函数以实现降序排序。
  5. 输出结果:分别输出升序和降序排序后的结果。

这个示例展示了如何在 C++ 中使用 sort 函数对数组或容器进行排序,并且可以指定排序顺序。

上一篇:c++随机数生成代码

下一篇:c++字符串类型

大家都在看

c++闭包

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

c++ 注释

c++如何判断素数

c++格式化字符串

c++ orm框架

c++ random函数用法

队列c++

c++freopen怎么用

c++virtual

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

Laravel 中文站