Call function on each element in a sequence with algorithm for_each - C++ STL Algorithm

C++ examples for STL Algorithm:for_each

Description

Call function on each element in a sequence with algorithm for_each

Demo Code

#include <iostream> 
#include <algorithm> // algorithm definitions 
#include <numeric> // accumulate is defined here 
#include <vector> 
#include <iterator> 
using namespace std; 

void outputSquare( int ); // output square of a value 

int main() //  ww w.j  a v  a  2  s  . c o m
{ 
   const int SIZE = 10; 
   int a1[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
   vector< int > v( a1, a1 + SIZE ); // copy of a1 
   ostream_iterator< int > output( cout, " " ); 

   // output square of every element in v 
   cout << "\n\nThe square of every integer in Vector v is:\n"; 
   for_each( v.begin(), v.end(), outputSquare ); 

}

// output square of argument 
void outputSquare( int value ) 
{ 
   cout << value * value << ' '; 
} // end function outputSquare

Result


Related Tutorials