Display each element in a sequence using for_each() algorithm. - C++ STL Algorithm

C++ examples for STL Algorithm:for_each

Description

Display each element in a sequence using for_each() algorithm.

Demo Code

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Display an int value.
void show(int i) {
   cout << i << " ";
}
// Keep a running sum of the values passed to i.
int summation(int i) {
   static int sum = 0;
   sum += i;//from ww w . j  av a 2  s. c o m
   return sum;
}
int main()
{
   vector<int> v;
   int i;
   for(i=1; i < 11; i++)
      v.push_back(i);
   cout << "Contents of v: ";
   for_each(v.begin(), v.end(), show);
   cout << "\n";
   for_each(v.begin(), v.end(), summation);
   cout << "Summation of v: " << summation(0);
   return 0;
}

Result


Related Tutorials