The Simple Functional Template Library
[[map]]
 

map

Definition

C<Y> map( C<X> container, F<X,Y> functor );

where :

  • C is a container type (template)
  • F is the functor type (template)
  • X is the type of objects in the input container
  • Y is the return type of the functor

Parameters

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

Return value

A container of type C holding objects of type Y

Description

Applies the functor to every element of the input container and returns a container holding the results.

Examples

// 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
}
 
map.txt · Last modified: 2007/08/24 23:31 (external edit)
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki