Calculate cube of each element in a sequence and place results in another sequence with algorithm transform. - C++ STL Algorithm

C++ examples for STL Algorithm:transform

Description

Calculate cube of each element in a sequence and place results in another sequence with algorithm transform.

Demo Code

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

int calculateCube( int ); // calculate cube of a value 

int main() /* w w  w  . j  av a2  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, " " ); 

   vector< int > cubes( SIZE ); // instantiate vector cubes 

   // calculate cube of each element in v; place results in cubes 
   transform( v.begin(), v.end(), cubes.begin(), calculateCube ); 
   cout << "\n\nThe cube of every integer in Vector v is:\n" ; 
   copy( cubes.begin(), cubes.end(), output ); 
   cout << endl; 
}

// return cube of argument 
int calculateCube( int value ) 
{ 
   return value * value * value; 
}

Result


Related Tutorials