transform() Function in C++
Posted by Superadmin on August 10 2022 05:28:50

transform() Function in C++

 

This C++ program illustrates the transform() algorithm. The program creates two vectors and transforms the third vector by inserting a value equal to an element from first vector raise to the power of element in second vector. The function power is passed as a predicate to the function transform().

 

Here is the source code of the C++ program which illustrates the transform() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to illustrate transform algorithm
  3.  */
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <vector>
  7. #include <functional>
  8. #include <iterator>
  9. #include <iomanip>
  10. #include <cmath>
  11. using namespace std;
  12.  
  13. typedef const vector <int>& vecref;
  14.  
  15. int power(int a, int b)
  16. {
  17.     return pow(a, b);
  18. }
  19.  
  20. void print(vecref a, vecref b, vecref c)
  21. {
  22.     cout << "b[i]   a[i]    c[i]" << endl; 
  23.     for(int i = 0; i < a.size(); i++)
  24.     {
  25.         cout << setw(2) << setfill(' ') << a[i] << "   ^   "
  26.              << setw(1) << setfill(' ') << b[i] << "   =  "
  27.              << setw(2) << setfill(' ') << c[i] << endl;
  28.     }
  29. }
  30.  
  31. int main()
  32. {
  33.     vector <int> a(10), b(10), c(10);
  34.  
  35.     for (int i = 0; i < 10 ;i++)
  36.     {
  37.         a[i] = (i % 2 + 1);
  38.         b[i] = (i % 3 + 1);
  39.     }
  40.     // Save the result in vector c
  41.     cout << "Transform operation" << endl;
  42.     transform(b.begin(), b.end(), a.begin(), c.begin(), power);
  43.     print(b, a, c);
  44. }

 

$ a.out
Transform operation
b[i]   a[i]    c[i]
 1   ^   1   =   1
 2   ^   2   =   4
 3   ^   1   =   3
 1   ^   2   =   1
 2   ^   1   =   2
 3   ^   2   =   9
 1   ^   1   =   1
 2   ^   2   =   4
 3   ^   1   =   3
 1   ^   2   =   1