std::transform() in C++
Hello everyone, in this tutorial we learn about the std::transform() function available in C++. The transform function is defined under the algorithm header file. The transform function is used to perform operations sequentially on all the elements of an array.
Transform () is used in two forms :
- Unary operation
- Binary operation
We will learn about both the operation with examples.
Unary Operation
The unary operation is applied to each element in the input array, and the result is stored in the result array. Only one array is involved in this operation. For example, if you want to increment array by 2 or find the cube root etc.
Synatx:
transform( inputBegIterator, inputEndIterator , OutputIterator, unaryOperation)
Code:
#include <iostream> #include <algorithm> using namespace std; int cube(int x){ return (x*x*x); } int main() { int n; std::cout<<"Enter the number of elements in array : "; std::cin>>n; int arr[n],res[n]; std::cout<<"Enter elements in array :"; for(int i = 0 ; i<n ; i++) //accepting array std::cin>>arr[i]; std::transform(arr,arr+n,res,cube); //transform function for unary operation std::cout<<"Cube roots of each elements are :"; for(int i=0;i<n;i++) std::cout<<res[i]<<"\n"; //displaying result array }
Output:
Enter the number of elements in array : 3 Enter elements in array : 1 2 3 Cube roots of each elements are : 1 8 27
Binary Operation
A binary operation is called on each element of the first input array and the respective element of the second input array. The output is stored in the output array. Two arrays are involved in the operation. For example the addition of two arrays.
Synatx:
transform( inputBegIterator1, inputEndIterator1, inputBegIterator2, OutputIterator, binaryOperation)
Code:
#include <iostream> #include <algorithm> using namespace std; int add(int x , int y){ return (x+y); } int main() { int n; std::cout<<"Enter the number of element in array : "; std::cin>>n; int arr1[n],arr2[n],res[n]; std::cout<<"Enter elements in array1 : "; for(int i = 0 ; i<n ; i++) //accepting array1 std::cin>>arr1[i]; std::cout<<"Enter elements in array2 : "; for(int i = 0 ; i<n ; i++) //accepting array2 std::cin>>arr2[i]; std::transform(arr1,arr1+n,arr2,res,add); //transform function for binary operation std::cout<<"Addition of array is : "; for(int i=0;i<n;i++) std::cout<<res[i]<<"\n"; //displaying result array }
Output:
Enter the number of element in array : 3 Enter elements in array1 : 1 2 3 Enter elements in array2 : 1 2 3 Addition of array is : 2 4 6
Leave a Reply