C++中的转换包含函数(SCAN)

转换包含在C++中的内置函数,它与包含“扫描”()相同,除了一个函数,首先应用于每个输入项。 它的功能是使用一元_op在第一个和最后一个元素之间转换每个元素,然后通过 二进制运算 具有特定的范围。一 包含全部费用 定义第i个输入元素包含在第i个和运算中。 我们可以选择init(初始值),并将结果写入从d_开始的范围。

null

语法:

template < class InputItrator, class OutputItrator,          class BinaryOperation, class UnaryOperation >OutputItrator transform_inclusive_scan( InputItrator first,                                         InputItrator last,                                        OutputItrator d_first,                                        BinaryOperation binary_op,                                        UnaryOperation unary_op                                      );

使用的参数:

  • 第一点也是最后一点:- 第一个和最后一个元素定义了元素和的范围。
  • d_首先:- 它是目的地范围的开始。
  • 一元运算:- 要应用于输入范围内每个元素的操作。
  • 二进制运算:- 要应用于一元_op的结果和其他二元_op的结果的操作,以及是否将提供init(初始值)。

类型要求:

  • 输入器 :Inputiterator是一个迭代器类,它能够读取指向的元素。如果我一次递增,那么所有其他副本都将无效,并且它对单次传递算法有效。
  • 输出者 :OutputIterator是一个可以写入指向元素的迭代器。

返回值: 对元素的迭代器,使其超过最后写入的元素。

注: 一元_op在该函数中是可选的,不适用于init。实际上,init参数终于出现了。

下面是上述问题的实现。

C++

// C++ program by used std::transform_inclusive_scan() function
// to transforms each and every elements between first
// and last with unary_op, then computes an inclusive prefix sum
#include <iostream>
#include <vector>
using namespace std;
namespace geeksInputIterator {
template < class InputItrator, class OutputItrator,
class BinaryOperation, class UnaryOperation>
OutputItrator transform_inclusive_scan(InputItrator first,
InputItrator last,
OutputItrator d_first,
BinaryOperation binary_op,
UnaryOperation unary_op)
{
*d_first = unary_op(*first);
first++;
d_first++;
for ( auto it = first; it != last; it++) {
// calculate the prefix sum
*d_first = binary_op(unary_op(*it), *(d_first - 1));
d_first++;
}
return d_first;
}
}
// Driver code
int main()
{
// input elements
vector< int > InputVector{ 11, 22, 33, 44, 55, 66, 77, 88 };
// OutputVector elements size
vector< int > OutputVector(8);
// inclusive transform function with begin and ending
geeksInputIterator::transform_inclusive_scan(InputVector.begin(),
InputVector.end(), OutputVector.begin(),
[]( auto xx, auto yy) {
return xx + yy;
},
[]( auto xx) {
return xx * xx;
});
// for loop for print output
for ( auto item : OutputVector) {
// Print the output item
cout << item << " " ;
}
// to move next line
cout << std::endl;
return 0;
}


输出:

121 605 1694 3630 6655 11011 16940 24684 

注: 上述程序可能无法在许多IDE上运行。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享