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
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.