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.

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
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 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.