F<X> apply( C<X> container, F<X> functor );
where :
Parameter | Description |
---|---|
container | an STL container holding objects type X |
functor | a functor taking a parameter of type X |
The functor given as argument
Applies the functor to each object in the container and returns the functor
// 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> ); }