The transform()
function in C++ sequentially applies an operation to the elements of an array(s) and then stores the result in another output array.
The transform function is used in two forms:
Unary operation: The operation is applied to each element in the input range, and the result is stored in the output array.
Binary Operation: A binary operation is called on each element of the first input range and the respective element of the second input range. The output is stored in the output array.
The following code demonstrates how a unary operation is applied to an input array. The transform()
function takes the pointer to the starting and ending position of a single input array and to the starting position of the output array.
#include <iostream>#include <algorithm> // std::transformusing namespace std;// Unary function applied by the transform functionint op_increment (int x) {x = x + 1;return x;}int main () {int n = 5; // Number of elements in the array.int input_array[] = {3, 6, 8, 13, 2};int output_array[n]; // The array that will store out resultstd::cout << "Input array:";for(int i=0; i<5; i++){cout << ' ' << input_array[i];}cout << '\n';// The function takes start and end positions of the// range on which we want to apply our function. It// also takes the starting position of our output// array and the function we want to apply to the array.transform (input_array, input_array+5, output_array, op_increment);std::cout << "The output array now contains:";for(int i=0; i<5; i++){cout << ' ' << output_array[i];}cout << '\n';return 0;}
When applying a binary function, the transform()
function takes the pointer to the starting and ending position of the first input array and to the starting position of the second input array. The function also takes the pointer to the start of our output array and to the binary function that we want to apply to our two input arrays.
#include <iostream>#include <algorithm> // std::transform#include <vector> // std::vectorusing namespace std;// Binary function applied by the transform functionint op_add (int i, int j) {return i+j;}int main () {int n = 5;int arr1[] = {1, 2, 3, 4, 5};int arr2[] = {6, 7, 8, 9, 10};int output[n];std::cout << "Input array1:";for(int i=0; i<n; i++){cout << ' ' << arr1[i];}cout << '\n';std::cout << "Input array2:";for(int i=0; i<n; i++){cout << ' ' << arr2[i];}cout << '\n';// The transform function takes start and end position// of first array, start position of second array,// start position of output array and the binary// function to apply to the input arrays.std::transform (arr1, arr1+n, arr2, output, op_add);std::cout << "Output array:";for(int i=0; i<5; i++){cout << ' ' << output[i];}cout << '\n';return 0;}
Free Resources