C<Y> map( C<X> container, F<X,Y> functor );
where :
Parameter | Description |
---|---|
container | an STL container of type C holding objects type X |
functor | a functor taking a parameter of type X and returning a value of type Y |
A container of type C holding objects of type Y
Applies the functor to every element of the input container and returns a container holding the results.
// source : examples/map_example.cpp #include <iostream> #include <vector> #include "sftl.h" using namespace std; // function that divides a number by 2 double halve( int x ) { return (double)x/2.0; } // function object that bounds a value struct BoundsChecker { int min, max; BoundsChecker( int min, int max ) : min(min), max(max) {} int operator () (int x) { return (x<min) ? min : ( (x>max) ? max : x ); } }; template<class T> void print( T x ) { cout << x << endl; } int main() { // create vector of numbers int numbers [] = {1,2,3,4,5,6,7,8,9}; vector<int> v_numbers( &numbers[0], &numbers[9] ); cout << "numbers :" << endl; apply( v_numbers, print<int> ); // divides numbers by 2 vector<double> halves = map( v_numbers, halve ); cout << "halves : " << endl; apply( halves, print<double> ); // prints 0.5 1 1.5 2 ... // getting bounded numbers vector<int> bounded_numbers = map<int>( v_numbers, BoundsChecker(3,7) ); cout << "bounded numbers : " << endl; apply( bounded_numbers, print<int> ); // prints 3 3 3 4 5 6 7 7 7 }