I l@ve RuBoard Previous Section Next Section

transform()

The first version of transform() invokes the unary operator passed to it on each element in the sequence. For example, given a sequence {0,1,1,2,3,5} and a function object Double, which doubles each element, the resulting sequence is {0,2,2,4,6,10}. The second version invokes the binary operator passed to it on the associated elements of a pair of sequences. For example, given the sequences {1,3,5,9} and {2,4,6,8}, and a function object AddAndDouble that adds the two elements and then doubles their sum, the resulting sequence is {6,14,22,34}. The resulting sequence is copied into the container pointed to by either the third iterator of the first version or the fourth iterator of the second.



#include <algorithm> 


int double_val( int val ) { return val + val; } 


int difference( int val1, int val2 ) { return abs( val1 - val2 ); } 





int ia[]  = { 3, 5, 8, 13, 21 }; 


vector<int> vec( 5 ), vec2( 5 ); 





// first version: 6 10 16 26 42 


transform( ia, ia+5, vec.begin(), double_val ); 





// second version: 3 5 8 13 21 


transform( ia, ia+5, vec.begin(), vec2.begin(), difference ); 
    I l@ve RuBoard Previous Section Next Section