std::stable_sort
来自cppreference.com
<tbody>
</tbody>
| 在标头 <algorithm> 定义
|
||
template< class RandomIt > void stable_sort( RandomIt first, RandomIt last ); |
(1) | (C++26 起为 constexpr) |
template< class ExecutionPolicy, class RandomIt > void stable_sort( ExecutionPolicy&& policy, RandomIt first, RandomIt last ); |
(2) | (C++17 起) |
template< class RandomIt, class Compare > void stable_sort( RandomIt first, RandomIt last, Compare comp ); |
(3) | (C++26 起为 constexpr) |
template< class ExecutionPolicy, class RandomIt, class Compare > void stable_sort( ExecutionPolicy&& policy, RandomIt first, RandomIt last, Compare comp ); |
(4) | (C++17 起) |
以非降序排序范围 [first, last) 中的元素。保证保持等价元素间的顺序。
3) 按
comp 进行排序。2,4) 同 (1,3),但按照
policy 执行。 这些重载只有在满足以下所有条件时才会参与重载决议:
|
|
(C++20 前) |
|
|
(C++20 起) |
如果满足以下任意条件,那么行为未定义:
|
(C++11 前) |
|
(C++11 起) |
参数
| first, last | - | 要排序的元素范围的迭代器对 |
| policy | - | 所用的执行策略 |
| comp | - | 比较函数对象(即满足比较 (Compare) 概念的对象),在第一参数小于(即先 序于)第二参数时返回 true。比较函数的签名应等价于如下:
虽然签名不必有 |
| 类型要求 | ||
-RandomIt 必须满足老式随机访问迭代器 (LegacyRandomAccessIterator) 。
| ||
-Compare 必须满足比较 (Compare) 。
| ||
复杂度
给定 N 为 last - first:
1,2) 在额外内存足够时应用 O(N·log(N)) 次
(N)) 次。
operator<(C++20 前)std::less{}(C++20 起) 进行比较,否则应用 O(N·log2(N)) 次。
3,4) 在额外内存足够时应用 O(N·log(N)) 次比较函数
(N)) 次。
comp,否则应用 O(N·log2(N)) 次。
异常
拥有名为 ExecutionPolicy 的模板形参的重载按下列方式报告错误:
- 如果作为算法一部分调用的函数的执行抛出异常,且
ExecutionPolicy是标准策略之一,那么调用 std::terminate。对于任何其他ExecutionPolicy,行为由实现定义。 - 如果算法无法分配内存,那么抛出 std::bad_alloc。
可能的实现
注解
此函数试图分配等于待排序序列长度的临时缓冲区。如果分配失败,那么就会选择较低效的算法。
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_constexpr_algorithms |
202306L |
(C++26) | constexpr 的稳定排序,重载 (1), (3)
|
示例
运行此代码
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <vector>
struct Employee
{
int age;
std::string name; // 不参与比较
};
bool operator<(const Employee& lhs, const Employee& rhs)
{
return lhs.age < rhs.age;
}
#if __cpp_lib_constexpr_algorithms >= 202306L
consteval auto get_sorted()
{
auto v = std::array{3, 1, 4, 1, 5, 9};
std::stable_sort(v.begin(), v.end());
return v;
}
static_assert(std::ranges::is_sorted(get_sorted()));
#endif
int main()
{
std::vector<Employee> v{{108, "Zaphod"}, {32, "Arthur"}, {108, "Ford"}};
std::stable_sort(v.begin(), v.end());
for (const Employee& e : v)
std::cout << e.age << ", " << e.name << '\n';
}
输出:
32, Arthur
108, Zaphod
108, Ford
参阅
| 将范围中前 N 个元素排序 (函数模板) | |
| 将范围按升序排序 (函数模板) |