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.

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.