Example of stl::functional

[ permalink ] [ download ]
#include <iostream>
//For the pow
#include <math.h>
// stl 
#include <vector>
#include <functional>

// Example of std::functional (functions templates) with the stl
// Using them with / without templates.

class Exponenciar : public std::binary_function<double, double, double> {
public:
  double operator()(double x, double y) { return pow(x, y); }
};

class Cuadrar : public std::unary_function <double, double> {
public:
  double operator() (double x){return (Exponenciar().operator()(x,2));}
};

template <signed E> 
class ExponenciarTemplate : public std::unary_function<double, double> {
public:
  double operator()(double x) { return pow(x, E); }
};


int main (int argc, char * argv [])
{
  std::vector <double> myvec;
  for (int i =0; i < 10; myvec.push_back(i++));
  std::transform(myvec.begin()
		,myvec.end()
		,myvec.begin()
		,Cuadrar());
  for (int x = 0; x < 10; std::cout<<myvec[x++]<<std::endl);
  std::transform(myvec.begin()
		,myvec.end()
		,myvec.begin()
		,ExponenciarTemplate<3>());
  for (int x = 0; x < 10; std::cout<<myvec[x++]<<std::endl);
  return 0;
}
hits counter