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

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.