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.
/*
* C++ Program to demonstrate using unary arithmetic function objects
*/
#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);
}
$ 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.
Related Posts:
- Check Programming Books
- Apply for C++ Internship
- Check Computer Science Books
- Apply for Computer Science Internship
- Check C++ Books