transform_inclusive_scan() function in C++
transform_inclusive_scan() is inbuilt function in C++ and its same as inclusive_scan(), except a unary function which is first applied to each input item.
Its functionality is to transform each and every element between first and last with unary_op then computes an inclusive prefix sum operation by the help of binary_op with a specific range. An inclusive defined the i-th input element is included in the i-th sum operation.
We can take an optional init(initial values)and writes the results to the range beginning at d_first.
Syntax:
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
);
Parameters Used:
- first and last:-The first and last elements define the range of an elements sum.
- d_first:-Its beginning of the destination range.
- unary_op:-Operation to be applied on each element in the input range.
- binary_op:-Operation to be applied to the result of unary_op and the results of other binary_op, and if init(initial val ) will be provided.
Type requirements:
- InputItrator: The Inputiterator is class of an Iterator and it’s able to read from the pointed to element. If once i have incremented then all others copies are invalidated and its validity for single pass algorithm.
- OutputItrator: The OutputIterator is an Iterator that can be written to the pointed element.
Return Values: An iterator to the element past the last element written.
Note: An unary_op is optional in this function and not applied to init. Actually, the init parameter appears at last.
Following is the implementation of the above problem.
C++
#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++) {
*d_first = binary_op(unary_op(*it), *(d_first - 1));
d_first++;
}
return d_first;
}
}
int main()
{
vector< int > InputVector{ 11, 22, 33, 44, 55, 66, 77, 88 };
vector< int > OutputVector(8);
geeksInputIterator::transform_inclusive_scan(InputVector.begin(),
InputVector.end(), OutputVector.begin(),
[]( auto xx, auto yy) {
return xx + yy;
},
[]( auto xx) {
return xx * xx;
});
for ( auto item : OutputVector) {
cout << item << " " ;
}
cout << std::endl;
return 0;
}
|
Output:
121 605 1694 3630 6655 11011 16940 24684
Note: Above program may not run on many IDE’s.
Last Updated :
23 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...