std::stable_partition
来自 cppreference.cn
定义于头文件 <algorithm> |
||
template< class BidirIt, class UnaryPred > BidirIt stable_partition( BidirIt first, BidirIt last, UnaryPred p ); |
(1) | (constexpr since C++26) |
template< class ExecutionPolicy, class BidirIt, class UnaryPred > BidirIt stable_partition( ExecutionPolicy&& policy, |
(2) | (since C++17) |
1) 重新排序范围
[
first,
last)
中的元素,使得谓词 p 返回 true 的所有元素位于谓词 p 返回 false 的元素之前。 元素的相对顺序被保留。2) 与 (1) 相同,但根据 policy 执行。
仅当满足以下所有条件时,此重载才参与重载解析
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 为 true。 |
(until C++20) |
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> 为 true。 |
(since C++20) |
如果满足以下任何条件,则行为未定义
|
(until C++11) |
|
(since C++11) |
内容 |
[编辑] 参数
first, last | - | 定义要重新排序的元素范围的迭代器对 |
policy | - | 要使用的执行策略 |
p | - | 一元谓词,如果元素应在其他元素之前排序,则返回 true。 对于类型为 |
类型要求 | ||
-BidirIt 必须满足 LegacyBidirectionalIterator 的要求。 | ||
-UnaryPred 必须满足 Predicate 的要求。 |
[编辑] 返回值
指向第二组的第一个元素的迭代器。
[编辑] 复杂度
给定 N 为 std::distance(first, last)
1) 恰好 N 次 p 的应用。
如果有足够的额外内存,则 O(N) 次交换,否则最多 N⋅log2(N) 次交换。
2) O(N) 次 p 的应用。
N⋅log(N) 次交换。
[编辑] 异常
带有名为 ExecutionPolicy
的模板参数的重载报告错误如下
- 如果作为算法一部分调用的函数的执行抛出异常,并且
ExecutionPolicy
是 标准策略 之一,则调用 std::terminate。 对于任何其他ExecutionPolicy
,行为是实现定义的。 - 如果算法无法分配内存,则抛出 std::bad_alloc。
[编辑] 注意
此函数尝试分配临时缓冲区。 如果分配失败,则选择效率较低的算法。
libc++ 和 libstdc++ 中的实现也接受由 LegacyForwardIterator 表示的范围作为扩展。
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_constexpr_algorithms |
202306L |
(C++26) | constexpr 稳定排序 (1) |
[编辑] 示例
运行此代码
#include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> v{0, 0, 3, -1, 2, 4, 5, 0, 7}; std::stable_partition(v.begin(), v.end(), [](int n) { return n > 0; }); for (int n : v) std::cout << n << ' '; std::cout << '\n'; }
输出
3 2 4 5 7 0 0 -1 0
[编辑] 缺陷报告
以下行为更改缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 2150 | C++98 | std::stable_partition 仅需要放置一个满足 p 的元素在一个不满足 p 的元素之前 |
修正了 要求 |
[编辑] 参见
将元素范围划分为两组 (函数模板) | |
(C++20) |
将元素划分为两组,同时保留其相对顺序 (算法函数对象) |