Vector Addition using for_each() Algorithm in C++

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

  1. /*
  2.  * C++ Program to Compute Sum of elements of vector using for_each()  algorithm
  3.  */ 
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <vector>
  7.  
  8. class Sum {
  9.     private:
  10.         int sum;
  11.     public:
  12.         Sum (int val = 0) : sum(val) {}
  13.         void operator() (int val) {
  14.             std::cout << val << " ";
  15.             sum = sum + val;
  16.         }
  17.         void print() const
  18.         {
  19.             std::cout << "\nSum of the elements = "
  20.                       << sum << std::endl;
  21.         }
  22. };
  23.  
  24. int main()  
  25. {
  26.     Sum s, a;
  27.     std::vector <int> v, x(5, 5);
  28.     v.push_back(1);
  29.     v.push_back(2);
  30.     v.push_back(3);
  31.     v.push_back(4);
  32.     v.push_back(5);
  33.  
  34.     std::cout << "Elements of vector : ";
  35.     s = for_each(v.begin(), v.end(), s);
  36.     s.print();
  37.     std::cout << "Elements of vector : ";
  38.     a = for_each(x.begin(), x.end(), a);
  39.     a.print();
  40.     return 0;
  41. }

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

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

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 & technical discussions at Telegram SanfoundryClasses.