C++(15): STL算法:排序(sort)

1. 简述

std::sort 是 C++ 标准库 <algorithm> 中提供的一个函数,用于对容器(如数组、向量等)中的元素进行排序。它基于比较操作对元素进行排序,通常使用高效的排序算法,如快速排序、归并排序或堆排序等。

在实际应用中,std::sort 通常会根据输入数据的大小和特性自适应地选择一种合适的排序算法。例如,对于小型数据集,它可能会选择插入排序或选择排序等简单算法,因为这些算法在小规模数据上通常具有较低的常数因子。对于大型数据集,它可能会选择快速排序、归并排序或堆排序等更高效的算法。

2. 原型

template<class RandomIt>

void sort( RandomIt first, RandomIt last );

template<class RandomIt, class Compare>

void sort( RandomIt first, RandomIt last, Compare comp );

****first 和 last:****这两个参数是迭代器,分别指向要排序序列的开始和结束。注意,last 指向的是序列"之后"的位置,所以序列中的元素范围实际上是 [first, last)。

****comp:****这是一个可选的比较函数或函数对象,用于定义排序的顺序。如果提供了这个参数,std::sort 会使用这个比较函数来确定元素的顺序。默认情况下,std::sort 使用 < 操作符来比较元素。

3. 稳定排序

有时候使用sort时,值相同的两个元素,在排序前后的顺序不一定相同,如何解决这个问题呢?答案是使用std::stable_sort

std::stable_sort 是 C++ 标准库 <algorithm> 头文件中提供的一个函数,用于对容器(如数组、向量等)中的元素进行稳定排序。与 std::sort 不同,std::stable_sort 保证了具有相同值的元素的相对顺序在排序后保持不变。

std::stable_sort的使用与std::sort一样,此处不过多赘述。

4. 排序例程

(1)排序数组(正向)

复制代码
int array[] = {3, 1, 5, 9, 5, 7, 9, 3, 5};

std::sort(array, array + sizeof(array) / sizeof(array[0]));

(2)排序数组(反向)

复制代码
int arr[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};

int n = sizeof(arr) / sizeof(arr[0]);

sort(arr, arr + n, greater<int>());

(3)vector排序

复制代码
std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};

std::sort(v.begin(), v.end());

(4)自定义数据排序

对自定义数据进行排序时,需要实现排序函数对象。

复制代码
#include <iostream>

#include <fstream>

#include <sstream>

#include <iomanip>

#include <algorithm>


typedef struct _Student

{

    std::string name;  

    int age;  

}Student;

 

bool compareByAge(const Student& a, const Student& b)

{

    return a.age < b.age;  

}  

 

int main(int argc, char* argv[])

{

    std::vector<Student> people;

    /** 加入一些学生信息. */  

    std::sort(people.begin(), people.end(), compareByAge);  

}
相关推荐
南郁6 小时前
007-nlohmann/json 项目应用-C++开源库108杰
c++·开源·json·nlohmann·现代c++·d2school·108杰
菠萝018 小时前
共识算法Raft系列(1)——什么是Raft?
c++·后端·算法·区块链·共识算法
海棠蚀omo8 小时前
C++笔记-C++11(一)
开发语言·c++·笔记
凌佚9 小时前
rknn优化教程(一)
c++·目标检测·性能优化
Lenyiin11 小时前
《 C++ 点滴漫谈: 四十 》文本的艺术:C++ 正则表达式的高效应用之道
c++·正则表达式·lenyiin
yxc_inspire13 小时前
基于Qt的app开发第十三天
c++·qt·app·tcp·面向对象
虾球xz13 小时前
CppCon 2015 学习:Concurrency TS Editor’s Report
开发语言·c++·学习
潇-xiao14 小时前
Qt 按钮类控件(Push Button 与 Radio Button)(1)
c++·qt
板鸭〈小号〉14 小时前
命名管道实现本地通信
开发语言·c++
YKPG15 小时前
C++学习-入门到精通【14】标准库算法
c++·学习·算法