C++ Program to Demonstrate using Unary Arithmetic Function Object

This C++ program demonstrates using unary arithmetic function object. Tbe program creates a vector with integer elements and negates them using ‘negate’ function object which is passed as a parameter to the transform algorithm which negates the corresponding elements and stores the value in the second vector.

Here is the source code of the C++ program which demonstrates using unary 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 unary 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)
  15. {
  16.     cout << "a[i]  negate(a[i])" << endl; 
  17.     for(int i = 0; i < a.size(); i++)
  18.     {
  19.         cout << setw(3) << setfill(' ') << a[i]
  20.              << setw(7) << setfill(' ') << b[i]
  21.              << endl;
  22.     }
  23. }
  24.  
  25. int main()
  26. {
  27.     vector <int> a(10), b(10);
  28.  
  29.     for (int i = 0; i < 10 ;i++)
  30.     {
  31.         a[i] = i + 1;
  32.     }
  33.     // Save the result in vector c
  34.     transform(a.begin(), a.end(), b.begin(), negate <int>());
  35.     cout << "Negation using \'negate\' arithmetic function object"
  36.          << endl;
  37.     print(a, b);
  38. }

$ a.out
Negation using 'negate' arithmetic function object
a[i]  negate(a[i])
  1     -1
  2     -2
  3     -3
  4     -4
  5     -5
  6     -6
  7     -7
  8     -8
  9     -9
 10    -10

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

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

If you find any mistake above, kindly email to [email protected]

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.