std::transform_exclusive_scan
來自 cppreference.com
定義於標頭檔案 <numeric> |
||
template< class InputIt, class OutputIt, class T, class BinaryOp, class UnaryOp > |
(1) | (C++17 起) (C++20 起為 constexpr) |
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T, |
(2) | (C++17 起) |
1) 使用 op 計算獨佔字首和。
對於
[
0,
std::distance(first, last))
中的每個整數 i,按順序執行以下操作:- 建立一個序列,該序列由 init 和按 unary_op 依次從
[
first,
iter)
元素轉換而來的值組成,其中 iter 是 first 的第 i 個迭代器。 - 計算序列在 binary_op 上的廣義非交換和。
- 將結果賦值給 *dest,其中 dest 是 d_first 的第 i 個迭代器。
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 起) |
序列在二元操作 binary_op 上的廣義非交換和定義如下:
- 如果序列只有一個元素,則和就是該元素的值。
- 否則,按順序執行以下操作:
- 從序列中選擇任意兩個相鄰元素 elem1 和 elem2。
- 計算 binary_op(elem1, elem2) 並用結果替換序列中的這兩個元素。
- 重複步驟 1 和 2,直到序列中只剩下一個元素。
如果 binary_op 不滿足結合律(例如浮點加法),則結果是不確定的。
如果以下任一值不能轉換為 `T`,則程式是病態的:
- binary_op(init, init)
- binary_op(init, unary_op(*first))
- binary_op(unary_op(*first), unary_op(*first))
如果滿足以下任何條件,則行為是未定義的:
-
T
不是 可移動構造 (MoveConstructible) 的。 - unary_op 或 binary_op 修改
[
first,
last)
中的任何元素。 - unary_op 或 binary_op 使
[
first,
last]
的任何迭代器或子範圍失效。
目錄 |
[編輯] 引數
first, last | - | 定義要求和元素的範圍的迭代器對 |
d_first | - | 目標範圍的起始,可以等於 first |
policy | - | 要使用的 執行策略 |
init | - | 初始值 |
unary_op | - | 將應用於輸入範圍每個元素的一元函式物件。返回型別必須可作為 binary_op 的輸入。 |
binary_op | - | 將應用於 unary_op 的結果、其他 binary_op 的結果和 init 的二元函式物件。 |
型別要求 | ||
-InputIt 必須滿足 LegacyInputIterator 的要求。 | ||
-OutputIt 必須滿足 LegacyOutputIterator 的要求。 | ||
-ForwardIt1, ForwardIt2 必須滿足 舊式前向迭代器 的要求。 |
[編輯] 返回值
指向最後一個寫入元素之後的元素的迭代器。
[編輯] 複雜度
給定 N 作為 std::distance(first, last)
1,2) 分別對 unary_op 和 binary_op 進行 O(N) 次應用。
[編輯] 異常
帶有名為 ExecutionPolicy
的模板引數的過載會按如下方式報告錯誤:
- 如果作為演算法一部分呼叫的函式丟擲異常,並且
ExecutionPolicy
是標準策略之一,則呼叫 std::terminate。對於任何其他ExecutionPolicy
,行為是實現定義的。 - 如果演算法未能分配記憶體,則丟擲 std::bad_alloc。
[編輯] 註記
unary_op 從不應用於 init。
[編輯] 示例
執行此程式碼
#include <functional> #include <iostream> #include <iterator> #include <numeric> #include <vector> int main() { std::vector data{3, 1, 4, 1, 5, 9, 2, 6}; auto times_10 = [](int x) { return x * 10; }; std::cout << "10 times exclusive sum: "; std::transform_exclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), 0, std::plus<int>{}, times_10); std::cout << "\n10 times inclusive sum: "; std::transform_inclusive_scan(data.begin(), data.end(), std::ostream_iterator<int>(std::cout, " "), std::plus<int>{}, times_10); std::cout << '\n'; }
輸出
10 times exclusive sum: 0 30 40 80 90 140 230 250 10 times inclusive sum: 30 40 80 90 140 230 250 310
[編輯] 參閱
計算一個範圍元素的部分和 (函式模板) | |
(C++17) |
類似於 std::partial_sum,從第 i 個和中排除第 i 個輸入元素 (函式模板) |
(C++17) |
應用一個可呼叫物件,然後計算包含掃描 (函式模板) |