C++ Program to Demonstrate using Binary Arithmetic Function Object

This C++ program demonstrates using binary arithmetic function object. Tbe program creates two vectors with integer elements and adds them using ‘plus’ function object which is passed as a parameter to the transform algorithm which adds the corresponding elements and stores the sum in the third vector.

Here is the source code of the C++ program which demonstrates using binary arithmetic function object. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

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

$ a.out
Addition using 'plus' arithmetic function object
a[i]  b[i]  c[i]
 1  +  1  =  2
 2  +  2  =  4
 3  +  3  =  6
 4  +  4  =  8
 5  +  1  =  6
 1  +  2  =  3
 2  +  3  =  5
 3  +  4  =  7
 4  +  1  =  5
 5  +  2  =  7

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

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

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest 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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.