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。 對於型別為(可能為 const) |
型別要求 | ||
-InputIt 必須滿足 LegacyInputIterator 的要求。 | ||
-OutputIt1, OutputIt2 必須滿足 LegacyOutputIterator 的要求。 | ||
-ForwardIt1, ForwardIt2, ForwardIt3 必須滿足 LegacyForwardIterator 的要求。 | ||
-UnaryPred 必須滿足 Predicate 的要求。 |
[編輯] 返回值
一個 std::pair,由指向 d_first_true 範圍末尾的迭代器和指向 d_first_false 範圍末尾的迭代器構造。
[編輯] 複雜度
精確地應用 p std::distance(first, last) 次。
對於過載 (2),如果 ForwardIt
的值型別不是 CopyConstructible,則可能存在效能開銷。
[編輯] 異常
帶有名為 ExecutionPolicy
的模板引數的過載會按如下方式報告錯誤:
- 如果在演算法作為函式呼叫的一部分執行時丟擲異常,並且
ExecutionPolicy
是標準策略之一,則呼叫 std::terminate。對於任何其他ExecutionPolicy
,行為由實現定義。 - 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[編輯] 可能實現
partition_copy (1) |
---|
template<class InputIt, class OutputIt1, class OutputIt2, class UnaryPred> constexpr //< since 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) |
複製一個範圍,並將元素分成兩組 (演算法函式物件) |