Namespaces
Variants

std::ranges::sort

从 zh.cppreference.net
 
 
算法库
受约束算法和范围上的算法 (C++20)
受约束算法,例如 ranges::copy、ranges::sort、...
排序及相关操作
划分操作
(C++11)    

排序操作
二分搜索操作
(在已划分范围上)
集合操作(在已排序范围上)
合并操作(在已排序范围上)
堆操作
最小/最大操作
(C++11)
(C++17)
字典序比较操作
排列操作


 
受约束算法
本菜单中的所有名称均属于命名空间 std::ranges
非修改序列操作
修改序列操作
划分操作
排序操作
二分搜索操作(在已排序范围上)
       
       
集合操作(在已排序范围上)
堆操作
最小/最大操作
       
       
排列操作
折叠操作
数值运算
(C++23)            
未初始化存储上的操作
返回类型
 
定义于头文件 <algorithm>
调用签名
template< std::random_access_iterator I, std::sentinel_for<I> S,
          class Comp = ranges::less, class Proj = std::identity >
requires std::sortable<I, Comp, Proj>
constexpr I 
    sort( I first, S last, Comp comp = {}, Proj proj = {} );
(1) (C++20 起)
template< ranges::random_access_range R, class Comp = ranges::less,
          class Proj = std::identity >
requires std::sortable<ranges::iterator_t<R>, Comp, Proj>
constexpr ranges::borrowed_iterator_t<R>
    sort( R&& r, Comp comp = {}, Proj proj = {} );
(2) (C++20 起)

将范围 [first, last) 中的元素以非降序排序。不保证保持等价元素的顺序。

如果对于任何指向序列的迭代器 comp 和任何非负整数 it,使得 n 是指向序列中元素的有效迭代器,it + n 的计算结果为 std::invoke(comp, std::invoke(proj, *(it + n)), std::invoke(proj, *it)),则序列相对于比较器 false 已排序。

1) 元素通过给定的二元比较函数 comp 进行比较。
2) 与 (1) 相同,但使用 r 作为源范围,就好像使用 ranges::begin(r) 作为 first 且使用 ranges::end(r) 作为 last。

本页描述的函数式实体是算法函数对象(非正式地称为niebloids),即:

参数

first, last - 定义待排序元素 范围 的迭代器-哨位对
r - 待排序的范围
comp - 应用于投影元素的比较器
proj - 应用于元素的投影器

返回值

一个等于 last 的迭代器。

复杂度

𝓞(N·log(N)) 次比较和投影操作,其中 N = ranges:: distance ( first, last ) 。

可能的实现

请注意,典型实现使用 内省排序 。另请参阅 MSVC STL 与 libstdc++ 中的实现。

struct sort_fn
{
    template<std::random_access_iterator I, std::sentinel_for<I> S,
             class Comp = ranges::less, class Proj = std::identity>
    requires std::sortable<I, Comp, Proj>
    constexpr I
        operator()(I first, S last, Comp comp = {}, Proj proj = {}) const
    {
        if (first == last)
            return first;
        I last_iter = ranges::next(first, last);
        ranges::make_heap(first, last_iter, std::ref(comp), std::ref(proj));
        ranges::sort_heap(first, last_iter, std::ref(comp), std::ref(proj));
        return last_iter;
    }
    template<ranges::random_access_range R, class Comp = ranges::less,
             class Proj = std::identity>
    requires std::sortable<ranges::iterator_t<R>, Comp, Proj>
    constexpr ranges::borrowed_iterator_t<R>
        operator()(R&& r, Comp comp = {}, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::move(comp), std::move(proj));
    }
};
inline constexpr sort_fn sort {};

注释

std::sort 使用 std::iter_swap 来交换元素,而 ranges::sort 则使用 ranges::iter_swap (该函数会为 iter_swap 执行 ADL,这一点与 std::iter_swap 不同)

示例

#include <algorithm>
#include <array>
#include <functional>
#include <iomanip>
#include <iostream>
void print(auto comment, auto const& seq, char term = ' ')
{
    for (std::cout << comment << '\n'; auto const& elem : seq)
        std::cout << elem << term;
    std::cout << '\n';
}
struct Particle
{
    std::string name; double mass; // MeV
    template<class Os> friend
    Os& operator<<(Os& os, Particle const& p)
    {
        return os << std::left << std::setw(8) << p.name << " : " << p.mass << ' ';
    }
};
int main()
{
    std::array s {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
    namespace ranges = std::ranges;
    ranges::sort(s);
    print("使用默认 operator< 进行排序", s);
    ranges::sort(s, ranges::greater());
    print("使用标准库比较函数对象进行排序", s);
    struct
    {
        bool operator()(int a, int b) const { return a < b; }
    } customLess;
    ranges::sort(s.begin(), s.end(), customLess);
    print("使用自定义函数对象进行排序", s);
    ranges::sort(s, [](int a, int b) { return a > b; });
    print("使用 lambda 表达式进行排序", s);
    Particle particles[]
    {
        {"Electron", 0.511}, {"Muon", 105.66}, {"Tau", 1776.86},
        {"Positron", 0.511}, {"Proton", 938.27}, {"Neutron", 939.57}
    };
    ranges::sort(particles, {}, &Particle::name);
    print("\n使用投影按名称排序", particles, '\n');
    ranges::sort(particles, {}, &Particle::mass);
    print("使用投影按质量排序", particles, '\n');
}

输出:

使用默认 operator< 进行排序
0 1 2 3 4 5 6 7 8 9
使用标准库比较函数对象进行排序
9 8 7 6 5 4 3 2 1 0
使用自定义函数对象进行排序
0 1 2 3 4 5 6 7 8 9
使用 lambda 表达式进行排序
9 8 7 6 5 4 3 2 1 0
使用投影按名称排序
Electron : 0.511
Muon     : 105.66
Neutron  : 939.57
Positron : 0.511
Proton   : 938.27
Tau      : 1776.86
使用投影按质量排序
Electron : 0.511
Positron : 0.511
Muon     : 105.66
Proton   : 938.27
Neutron  : 939.57
Tau      : 1776.86

另见

对范围中的前 N 个元素进行排序
(算法函数对象)
对范围中的元素进行排序,同时保持等价元素间的相对顺序
(算法函数对象)
将范围中的元素分成两组
(算法函数对象)
对范围中的元素进行排序
(函数模板)