当前位置: 首页 > news >正文

FX-std::vector排序

在 C++ 中,std::vector 可以使用标准库中的 std::sort 函数对元素进行排序。std::sort 位于 <algorithm> 头文件中,是一个非常高效的排序算法(通常是快速排序或混合排序)。

以下是 std::sort 的基本用法:


1. 包含头文件

#include <algorithm> // for std::sort
#include <vector>

2. 默认排序(升序)

std::sort 默认使用 < 运算符对元素进行升序排序。

std::vector<int> vec = {5, 2, 9, 1, 5, 6};

// 默认升序排序
std::sort(vec.begin(), vec.end());

// 输出结果
for (int value : vec) {
    std::cout << value << " ";
}
// 输出: 1 2 5 5 6 9

3. 降序排序

可以通过传递一个自定义的比较函数来实现降序排序。C++ 提供了 std::greater 来简化这一操作。

#include <functional> // for std::greater

std::vector<int> vec = {5, 2, 9, 1, 5, 6};

// 降序排序
std::sort(vec.begin(), vec.end(), std::greater<int>());

// 输出结果
for (int value : vec) {
    std::cout << value << " ";
}
// 输出: 9 6 5 5 2 1

4. 自定义排序规则

如果需要根据特定规则排序,可以传递一个自定义的比较函数或 lambda 表达式。

示例 1:按绝对值排序
std::vector<int> vec = {-5, 2, -9, 1, 5, 6};

// 按绝对值升序排序
std::sort(vec.begin(), vec.end(), [](int a, int b) {
    return abs(a) < abs(b);
});

// 输出结果
for (int value : vec) {
    std::cout << value << " ";
}
// 输出: 1 2 -5 5 6 -9std::vector<int> vec = {-5, 2, -9, 1, 5, 6};
示例 2:按字符串长度排序
std::vector<std::string> vec = {"apple", "banana", "kiwi", "mango"};

// 按字符串长度升序排序
std::sort(vec.begin(), vec.end(), [](const std::string& a, const std::string& b) {
    return a.length() < b.length();
});

// 输出结果
for (const std::string& str : vec) {
    std::cout << str << " ";
}
// 输出: kiwi mango apple banana

5. 部分排序

如果只需要对部分元素进行排序,可以使用 std::partial_sort

std::vector<int> vec = {5, 2, 9, 1, 5, 6};

// 对前 3 个元素进行排序
std::partial_sort(vec.begin(), vec.begin() + 3, vec.end());

// 输出结果
for (int value : vec) {
    std::cout << value << " ";
}
// 输出: 1 2 5 9 5 6

6. 排序自定义对象

如果 std::vector 存储的是自定义对象,可以通过重载 < 运算符或提供自定义比较函数来排序。

示例:按对象的某个成员变量排序
#include <iostream>
#include <vector>
#include <algorithm>

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

    // 按年龄升序排序
    std::sort(people.begin(), people.end());

    // 输出结果
    for (const Person& p : people) {
        std::cout << p.name << " (" << p.age << ")\n";
    }
    // 输出:
    // Bob (20)
    // Alice (25)
    // Charlie (30)

    return 0;
}

7. 性能说明

  • std::sort 的时间复杂度为 O(Nlog⁡N)O(NlogN),其中 NN 是元素的数量。

  • std::sort 是不稳定的排序算法。如果需要稳定排序(保持相等元素的相对顺序),可以使用 std::stable_sort


8. 完整示例

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional> // for std::greater

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

    // 默认升序排序
    std::sort(vec.begin(), vec.end());
    std::cout << "Ascending: ";
    for (int value : vec) {
        std::cout << value << " ";
    }
    std::cout << "\n";

    // 降序排序
    std::sort(vec.begin(), vec.end(), std::greater<int>());
    std::cout << "Descending: ";
    for (int value : vec) {
        std::cout << value << " ";
    }
    std::cout << "\n";

    return 0;
}

总结

  • std::sort 是 C++ 中最常用的排序函数,适用于 std::vector 和其他容器。

  • 默认是升序排序,可以通过 std::greater 或自定义比较函数实现降序或其他规则排序。

  • 对于自定义对象,可以通过重载 < 运算符或提供比较函数来排序。

http://www.dtcms.com/a/67414.html

相关文章:

  • SQLite Truncate Table
  • Selenium Manager和webdriver manager的区别与联系
  • chebykan阅读收尾
  • 数组逆序重存放(信息学奥赛一本通-1105)
  • 版本控制器Git(5)
  • 问deepseek: OpenFOAM并行分区后,是如何实现ldumatrix矩阵向量乘法计算逻辑的?
  • 05延迟任务精准发布文章(redis实现延迟任务、分布式锁)
  • 学习文章:Spring Boot 中如何使用 `@Async` 实现异步处理
  • vue项目清理node_modules缓存
  • 防汛应急包,快速响应,守护安全
  • 什么是后训练?大语言模型训练后优化方法综述,87页pdf
  • 从零开始学习机器人---如何高效学习机械原理
  • 3.JVM-内部结构
  • 批量删除 Excel 表格中的重复行
  • Python 进程与线程-分布式进程
  • MC34063数据手册解读:功能、应用与设计指南
  • Flutter Dart 运算符全面解析
  • ⭐算法OJ⭐汉明距离【位操作】(C++ 实现)Hamming Distance
  • 如何解决Redis的缓存雪崩、缓存击穿、缓存穿透?
  • 前端UI编程基础知识:基础三要素(结构→表现→行为)
  • CNN-BiLSTM、BiLSTM、CNN多变量时间序列光伏功率预测Matlab
  • SpringCloud一些基础概念(自用扫盲)
  • Pytest自动化测试框架pytest-xdist分布式测试插件
  • 医院HIS系统的安全解决方案
  • 医药制造行业现状 医药制造行业内检实验室LIMS
  • 蓝桥杯备考:set容器用法(lower_bound)---营业额统计
  • 30、Vuex 为啥可以进行缓存处理
  • ES6回顾:闭包->(优点:实现工厂函数、记忆化和异步实现)、(应用场景:Promise的then与catch的回调、async/await、柯里化函数)
  • 二进制求和(js实现,LeetCode:67)
  • 如何在宝塔mysql修改掉3306端口