std:: partition_copy
|
定义于头文件
<algorithm>
|
||
|
template
<
class
InputIt,
class
OutputIt1,
class
OutputIt2,
class
UnaryPred
>
|
(1) |
(C++11 起)
(C++20 起为 constexpr) |
|
template
<
class
ExecutionPolicy,
class
ForwardIt1,
class
ForwardIt2,
class
ForwardIt3,
class
UnaryPred
>
|
(2) | (C++17 起) |
[
first
,
last
)
中的元素根据谓词
p
的返回值复制到两个不同区间。
- 满足谓词 p 的元素被复制到起始于 d_first_true 的区间。
- 其余元素被复制到起始于 d_first_false 的区间。
|
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 起) |
如果 * first 无法写入 d_first_true 或 d_first_false ,则程序格式错误。
在输入范围和两个输出范围中,如果任意两个范围存在重叠,则行为未定义。
目录 |
参数
| first, last | - | 定义待复制元素源 范围 的迭代器对 |
| d_first_true | - | 满足 p 条件的元素输出范围的起始位置 |
| d_first_false | - | 不满足 p 条件的元素输出范围的起始位置 |
| policy | - | 使用的 执行策略 |
| p | - |
一元谓词,若元素应置于 d_first_true 则返回
true
。
表达式
p
(
v
)
必须可转换为
bool
,其中
|
| 类型要求 | ||
-
InputIt
必须满足
LegacyInputIterator
的要求。
|
||
-
OutputIt1, OutputIt2
必须满足
LegacyOutputIterator
的要求。
|
||
-
ForwardIt1, ForwardIt2, ForwardIt3
必须满足
LegacyForwardIterator
的要求。
|
||
-
UnaryPred
必须满足
Predicate
的要求。
|
||
返回值
一个从指向 d_first_true 范围末尾的迭代器和指向 d_first_false 范围末尾的迭代器构造的 std::pair 。
复杂度
恰好需要 std:: distance ( first, last ) 次对 p 的调用。
对于重载
(2)
,如果
ForwardIt
的值类型不满足
可复制构造
要求,则可能存在性能开销。
异常
带有名为
ExecutionPolicy
模板参数的重载按以下方式报告错误:
-
如果作为算法一部分调用的函数执行抛出异常,且
ExecutionPolicy是某个 标准策略 ,则调用 std::terminate 。对于其他任何ExecutionPolicy,其行为由实现定义。 - 如果算法无法分配内存,则抛出 std::bad_alloc 。
可能的实现
| partition_copy (1) |
|---|
template<class InputIt, class OutputIt1, class OutputIt2, class UnaryPred> constexpr //< 自 C++20 起 std::pair<OutputIt1, OutputIt2> partition_copy(InputIt first, InputIt last, OutputIt1 d_first_true, OutputIt2 d_first_false, UnaryPred p) { for (; first != last; ++first) { if (p(*first)) { *d_first_true = *first; ++d_first_true; } else { *d_first_false = *first; ++d_first_false; } } return std::pair<OutputIt1, OutputIt2>(d_first_true, d_first_false); } |
示例
#include <algorithm> #include <iostream> #include <utility> void print(auto rem, const auto& v) { for (std::cout << rem; const auto& x : v) std::cout << x << ' '; std::cout << '\n'; } int main() { int arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int true_arr[5] = {0}; int false_arr[5] = {0}; std::partition_copy(std::begin(arr), std::end(arr), std::begin(true_arr), std::begin(false_arr), [](int i) { return 4 < i; }); print("true_arr: ", true_arr); print("false_arr: ", false_arr); }
输出:
true_arr: 5 6 7 8 9 false_arr: 0 1 2 3 4
缺陷报告
下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
| 缺陷报告 | 应用于 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| P0896R4 |
C++11
C++17 |
1.
InputIt
(C++11)/
ForwardIt1
(C++17) 的值类型
被要求为 CopyAssignable 2. 两个输出范围允许重叠 |
1. 不再要求
2. 此情况下的行为 是未定义的 |
参见
|
将元素范围划分为两组
(函数模板) |
|
|
划分元素为两组并保持其相对顺序
(函数模板) |
|
|
(C++11)
|
复制元素范围到新位置
(函数模板) |
|
复制元素范围并跳过满足特定条件的元素
(函数模板) |
|
|
(C++20)
|
复制范围并将元素划分为两组
(算法函数对象) |