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

c++sort函数的用法

作者:空白篇pia~   发布日期:2026-06-04   浏览:42

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

using namespace std;

// 自定义排序规则,按降序排列
bool compare(int a, int b) {
    return a > b;
}

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

    // 使用默认升序排序
    sort(numbers.begin(), numbers.end());
    cout << "升序排序后的结果: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;

    // 使用自定义排序规则进行降序排序
    sort(numbers.begin(), numbers.end(), compare);
    cout << "降序排序后的结果: ";
    for (int num : numbers) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

解释说明:

  1. 包含头文件#include <algorithm> 是为了使用 std::sort 函数。
  2. 自定义排序规则compare 函数用于实现降序排序。它返回 true 时,表示第一个参数应该排在第二个参数之前。
  3. 默认升序排序sort(numbers.begin(), numbers.end()) 按照默认的升序规则对向量进行排序。
  4. 自定义排序sort(numbers.begin(), numbers.end(), compare) 使用自定义的比较函数 compare 对向量进行降序排序。

这段代码展示了如何使用 C++ 的 sort 函数进行升序和降序排序。

上一篇:c++构造函数

下一篇:c++20

大家都在看

c++闭包

c++向上取整的代码

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

c++ 注释

c++如何判断素数

c++怎么输入字符串

c++ functional

c++框架代码

c++格式化字符串

c++ orm框架

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

Laravel 中文站