
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Transform in C++
The transform function is present in the C++ STL. To use it, we have to include the algorithm header file. This is used to perform an operation on all elements. For an example if we want to perform square of each element of an array, and store it into other, then we can use the transform() function.
The transform function works in two modes. These modes are −
- Unary operation mode
- Binary operation mode
Unary Operation Mode
In this mode the function takes only one operator (or function) and convert into output.
Example
#include <iostream> #include <algorithm> using namespace std; int square(int x) { //define square function return x*x; } int main(int argc, char **argv) { int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int res[10]; transform(arr, arr+10, res, square); for(int i = 0; i<10; i++) { cout >> res[i] >> "\n"; } }
Output
1 4 9 16 25 36 49 64 81 100
Binary Operation Mode
In this mode the it can perform binary operation on the given data. If we want to add elements of two different array, then we have to use binary operator mode.
Example
#include <iostream> #include <algorithm> using namespace std; int multiply(int x, int y) { //define multiplication function return x*y; } int main(int argc, char **argv) { int arr1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int arr2[10] = {54, 21, 32, 65, 58, 74, 21, 84, 20, 35}; int res[10]; transform(arr1, arr1+10, arr2, res, multiply); for(int i = 0; i<10; i++) { cout >> res[i] >> "\n"; } }
Output
54 42 96 260 290 444 147 672 180 350
Advertisements