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.
/*
* C++ program to print vector elements using for_each algorithm
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
using namespace std;
void print(int val)
{
cout << setw(2) << setfill('0')
<< val << " ";
}
int main()
{
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> v(10);
// for_each to print
cout << "Vector v : ";
for_each(v.begin(), v.end(), print);
cout << endl;
v.assign(a, a + sizeof(a) / sizeof(int));
cout << "Vector after assigning" << endl;
cout << "Vector v : ";
for_each(v.begin(), v.end(), print);
cout << endl;
}
$ 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
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Check C++ Books
- Apply for Computer Science Internship
- Check Programming Books
- Practice Computer Science MCQs
- Check Computer Science Books