This C++ program computes the sum of integer elements of vector using for_each algorithm. The algorithm uses an auxiliary function object. The data member sum is initialized to zero and the operator is called with every integer element of the vector which is added to the data member. The value of the sum is printed.
Here is the source code of the C++ program computes the sum of integer elements of vector using for_each algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to Compute Sum of elements of vector using for_each() algorithm
*/
#include <iostream>
#include <algorithm>
#include <vector>
class Sum {
private:
int sum;
public:
Sum (int val = 0) : sum(val) {}
void operator() (int val) {
std::cout << val << " ";
sum = sum + val;
}
void print() const
{
std::cout << "\nSum of the elements = "
<< sum << std::endl;
}
};
int main()
{
Sum s, a;
std::vector <int> v, x(5, 5);
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
std::cout << "Elements of vector : ";
s = for_each(v.begin(), v.end(), s);
s.print();
std::cout << "Elements of vector : ";
a = for_each(x.begin(), x.end(), a);
a.print();
return 0;
}
$ a.out Elements of vector : 1 2 3 4 5 Sum of the elements = 15 Elements of vector : 5 5 5 5 5 Sum of the elements = 25
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]Related Posts:
- Check C++ Books
- Practice Computer Science MCQs
- Check Programming Books
- Practice Programming MCQs
- Check Computer Science Books