找回密码
 register

QQ登录

只需一步,快速开始

查看: 6|回复: 0

[C++] std::sort 数组排序函数 <algorithm>

[复制链接]

[C++] std::sort 数组排序函数 <algorithm>

[复制链接]
  • 打卡等级:热心大叔
  • 打卡总天数:155
  • 打卡月天数:4
  • 打卡总奖励:154
  • 最近打卡:2025-04-06 09:07:37
Waylee

主题

0

回帖

1万

积分

仙帝

积分
18941
Waylee 2025-4-6 09:26 | 显示全部楼层 |阅读模式 | Google Chrome | Windows 10

马上注册,查看网站隐藏内容!!

您需要 登录 才可以下载或查看,没有账号?register

×

0. 简介

std::sort 是 C++ 标准模板库(STL)中提供的一个排序算法,定义在 <algorithm> 头文件中。它用于对指定范围内的元素进行排序,要求传入的迭代器为随机访问迭代器(如 vector、deque 等)。默认情况下,std::sort 使用元素的 < 运算符进行比较。

以下是关于C++标准库中std::sort函数的详细教程:

1. 基本用法

#include <algorithm>  // 必须包含的头文件
#include <iostream>
#include <vector>

int main() {
    int arr[] = {5, 2, 8, 1, 3};
    int size = sizeof(arr) / sizeof(arr[0]);

    // 对数组排序
    std::sort(arr, arr + size);

    // 输出结果: 1 2 3 5 8
    for(int i = 0; i < size; i++) {
        std::cout << arr[i] << " ";
    }

    return 0;
}

2. 对容器排序

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> vec = {5, 2, 8, 1, 3};

    // 对vector排序
    std::sort(vec.begin(), vec.end());

    return 0;
}

3. 自定义排序规则

#include <algorithm>
#include <vector>

// 自定义比较函数
bool descending(int a, int b) {
    return a > b;  // 降序排列
}

int main() {
    std::vector<int> vec = {5, 2, 8, 1, 3};

    // 使用自定义比较函数
    std::sort(vec.begin(), vec.end(), descending);

    // 使用lambda表达式
    std::sort(vec.begin(), vec.end(), [](int a, int b) {
        return a < b;  // 升序排列
    });

    return 0;
}

4. 对结构体/类排序

#include <algorithm>
#include <vector>

struct Person {
    std::string name;
    int age;

    // 重载<运算符
    bool operator<(const Person& other) const {
        return age < other.age;
    }
};

int main() {
    std::vector<Person> people = {{"Alice", 25}, {"Bob", 20}, {"Charlie", 30}};

    // 方法1: 使用重载的<运算符
    std::sort(people.begin(), people.end());

    // 方法2: 使用lambda表达式
    std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) {
        return a.name < b.name;  // 按姓名排序
    });

    return 0;
}

5. 部分排序

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> vec = {5, 2, 8, 1, 3, 9, 4};

    // 只对前4个元素排序
    std::sort(vec.begin(), vec.begin() + 4);

    // 输出结果: 1 2 5 8 3 9 4
    for(int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

关键点说明:

  1. std::sort需要#include <algorithm>
  2. 参数是迭代器范围:begin()end()
  3. 默认是升序排序
  4. 时间复杂度:O(N log N)
  5. 是不稳定排序(如需稳定排序,使用std::stable_sort

需要任何特定方面的更详细解释吗?

您需要登录后才可以回帖 登录 | register

本版积分规则

雪舞知识库 | 浙ICP备15015590号-1 | 萌ICP备20232229号|浙公网安备33048102000118号 |天天打卡

GMT+8, 2025-4-7 13:49 , Processed in 0.112937 second(s), 7 queries , Redis On.

Powered by XueWu Licensed

Copyright © Tencent Cloud.

快速回复 返回顶部 返回列表