Namespaces
Variants

std:: stable_partition

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
stable_partition
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
定义于头文件 <algorithm>
template < class BidirIt, class UnaryPred >
BidirIt stable_partition ( BidirIt first, BidirIt last, UnaryPred p ) ;
(1) (自 C++26 起为 constexpr)
template < class ExecutionPolicy, class BidirIt, class UnaryPred >

BidirIt stable_partition ( ExecutionPolicy && policy,

BidirIt first, BidirIt last, UnaryPred p ) ;
(2) (自 C++17 起)
1) 对范围 [ first , last ) 内的元素进行重新排序,使得所有谓词 p 返回 true 的元素位于谓词 p 返回 false 的元素之前。元素的相对顺序保持不变。
2) (1) 相同,但根据 policy 执行。
此重载仅在满足以下所有条件时参与重载决议:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> true

(C++20 前)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> true

(C++20 起)

若满足以下任一条件,则行为未定义:

(C++11 前)
(C++11 起)

目录

参数

first, last - 定义待重排元素 范围 的迭代器对
policy - 要使用的 执行策略
p - 一元谓词,若元素应排序于其他元素之前则返回​ true

表达式 p ( v ) 必须可转换为 bool ,其中 v 为类型(可能为 const) VT 的参数, VT BidirIt 的值类型,且与 值类别 无关,同时不得修改 v 。因此不允许参数类型为 VT & ,也不允许为 VT (除非对于 VT 移动操作等价于拷贝操作) (C++11 起) 。 ​

类型要求
-
BidirIt 必须满足 LegacyBidirectionalIterator 的要求。
-
UnaryPred 必须满足 Predicate 的要求。

返回值

指向第二组第一个元素的迭代器。

复杂度

给定 N std:: distance ( first, last )

1) 恰好 N 次对 p 的应用。
O(N) 次交换(若有足够额外内存),否则最多 N⋅log 2 (N) 次交换。
2) O(N) 次对 p 的调用。
N⋅log(N) 次交换。

异常

带有名为 ExecutionPolicy 模板参数的重载按以下方式报告错误:

  • 如果作为算法一部分调用的函数执行抛出异常,且 ExecutionPolicy 是某个 标准策略 ,则调用 std::terminate 。对于其他任何 ExecutionPolicy ,其行为由实现定义。
  • 如果算法无法分配内存,则抛出 std::bad_alloc

注释

此函数尝试分配临时缓冲区。若分配失败,将选择效率较低的算法。

libc++ libstdc++ 中的实现还通过扩展功能接受由 LegacyForwardIterator s 表示的区间范围。

功能测试 标准 功能
__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++ 标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 2150 C++98 std::stable_partition 仅要求将满足 p 的一个元素
置于不满足 p 的元素之前
修正了
该要求

参见

将元素范围划分为两组
(函数模板)
将元素划分为两组并保持其相对顺序
(算法函数对象)