The Simple Functional Template Library
[[apply]]
 

apply

Definition

F<X> apply( C<X> container, F<X> functor );

where :

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

Parameters

Parameter Description
container an STL container holding objects type X
functor a functor taking a parameter of type X

Return value

The functor given as argument

Description

Applies the functor to each object in the container and returns the functor

Examples

// source : examples/apply_example.cpp
#include <iostream>
#include <vector>
#include <functional>
#include "sftl.h"
 
using namespace std;
 
// Soldier class
 
struct Soldier {
 
    int ammunition;
 
    Soldier( int ammo ) : ammunition(ammo) {};
 
    void fire() {  
        cout << "fire!" << endl; 
        --ammunition;
    }
};
 
 
// prints soldier ammunition  (function functor)
 
void print_ammo( Soldier& soldier ) {
    cout << "ammo : " << soldier.ammunition << endl;
}
 
// counter struct (stateful function object)
 
struct AmmoCounter : public unary_function<Soldier,void> {
 
    int total_ammo;
 
    AmmoCounter() : total_ammo(0) {}
 
    void operator () (Soldier& soldier) {
        total_ammo+= soldier.ammunition;
    }
};
 
 
int main() {
 
    vector<Soldier*> soldiers;
    soldiers.push_back( new Soldier(5) );
    soldiers.push_back( new Soldier(2) );
    soldiers.push_back( new Soldier(7) );
    soldiers.push_back( new Soldier(1) );
 
    // print ammunitions
    apply( soldiers, print_ammo );
 
    // fire all
    apply( soldiers, &Soldier::fire );
 
    // count remaining ammo
    AmmoCounter counter = apply( soldiers, AmmoCounter() );
    cout << "total remaining ammo : " << counter.total_ammo << endl; 
 
    // release allocated memory for soldiers
    apply( soldiers, delete_pointer<Soldier> );
}
 
apply.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