C++ Program to Demonstrate using Unary Arithmetic Function Object

bookmark

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
#include <iterator>
#include <iomanip>
using namespace std;
 
typedef const vector <int>& vecref;
 
void print(vecref a, vecref b)
{
    cout << "a[i]  negate(a[i])" << endl; 
    for(int i = 0; i < a.size(); i++)
    {
        cout << setw(3) << setfill(' ') << a[i]
             << setw(7) << setfill(' ') << b[i]
             << endl;
    }
}
 
int main()
{
    vector <int> a(10), b(10);
 
    for (int i = 0; i < 10 ;i++)
    {
        a[i] = i + 1;
    }
    // Save the result in vector c
    transform(a.begin(), a.end(), b.begin(), negate <int>());
    cout << "Negation using \'negate\' arithmetic function object"
         << endl;
    print(a, b);
}

 

Output:

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