Vector Elements using for_each() Algorithm in C++

This C++ program prints the elements of vector using for_each() algorithm. The program creates a vector, instantiates the value of elements using assign member function and prints the vector elements using for_each algorithm. The for_each function uses a predicate to print element by element as the iterator goes through the vector.

Here is the source code of the C++ program which prints the 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 print vector elements using for_each algorithm
  3.  */
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <vector>
  7. #include <iomanip>
  8. using namespace std;
  9.  
  10. void print(int val)
  11. {
  12.     cout << setw(2) << setfill('0')
  13.          << val << "  ";
  14. }
  15.  
  16. int main()
  17. {
  18.     int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  19.     vector<int> v(10);
  20.  
  21.     // for_each to print
  22.     cout << "Vector v : ";
  23.     for_each(v.begin(), v.end(), print);
  24.     cout << endl;
  25.     v.assign(a, a + sizeof(a) / sizeof(int));
  26.     cout << "Vector after assigning" << endl;
  27.     cout << "Vector v : ";
  28.     for_each(v.begin(), v.end(), print);
  29.     cout << endl;
  30. }

$ a.out
Vector v : 00  00  00  00  00  00  00  00  00  00  
Vector after assigning
Vector v : 01  02  03  04  05  06  07  08  09  10

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification 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 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.