std::transform_exclusive_scan
来自 cppreference.cn
定义于头文件 <numeric> |
||
template< class InputIt, class OutputIt, class T, class BinaryOp, class UnaryOp > |
(1) | (since C++17) (constexpr since C++20) |
template< class ExecutionPolicy, class ForwardIt1, class ForwardIt2, class T, |
(2) | (since C++17) |
1) 使用 op 计算排他的前缀和。
对于
[
0,
std::distance(first, last))
中的每个整数 i,按顺序执行以下操作- 创建一个序列,该序列由 init 开始,后跟通过 unary_op 依序从
[
first,
iter)
的元素变换得到的值,其中 iter 是 first 的第 ith 个迭代器。 - 计算序列在 binary_op 上的广义非交换和。
- 将结果赋值给 *dest,其中 dest 是 d_first 的第 ith 个迭代器。
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) |
序列元素在二元运算 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 | - | 将应用于输入范围中每个元素的一元函数对象 (FunctionObject)。 返回类型必须可以作为 binary_op 的输入。 |
binary_op | - | 将应用于 unary_op 的结果、其他 binary_op 的结果和 init 的二元函数对象 (FunctionObject)。 |
类型要求 | ||
-InputIt 必须满足 旧式输入迭代器 (LegacyInputIterator) 的要求。 | ||
-OutputIt 必须满足 旧式输出迭代器 (LegacyOutputIterator) 的要求。 | ||
-ForwardIt1, ForwardIt2 必须满足 旧式前向迭代器 (LegacyForwardIterator) 的要求。 |
[编辑] 返回值
指向写入的最后一个元素之后元素的迭代器。
[编辑] 复杂度
给定 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,从第 ith 个和中排除第 ith 个输入元素 (函数模板) |
(C++17) |
应用可调用对象,然后计算包含扫描 (函数模板) |