Is there a way to call std :: transform with a function with multiple arguments

Hello, I have a function whose signature

std :: string f (double x, double param1, double param2, double param3);

I would like to call it the value of std :: vector x for the parameter x, using something like std :: transform for the specific value of param1, param2 and param3.

This will be the equivalent:

double param1(1.); double param2(1.1); double param3(1.2); std::vector<std::string> results(); for (std::vector<double>::const_iterator it = xvalues.begin() ; it != xvalues.end() ; ++xvalues) { results.push_back(f(*it, param1, param2, param3); } 

How can this be done more elegantly?

Regards Tony

+7
c ++
source share
3 answers

You should look into boost :: bind , which will allow you, as the name indicates, to "bind" the arguments to your f function:

  std::transform([...], boost::bind(&f, _1, param1, param2, param3)); 

The result of this binding is a unary function ( _1 is a placeholder for the argument with which it should be called): all other parameters will have fixed values param1 , param2 , param3 .

+16
source share

And for completeness, C ++ 0x version, or what is the fuss about lambda?

 std::transform([...], [=](double i){ return f(i, param1, param2, param3); }); 
+7
source share

As a recommended method, icecrime boost::bind would be a better option. However, if you cannot use boost for some reason, you can always do this using a user-defined functor as follows:

 using namespace std; string f(double x, double param1, double param2, double param3) { return string(); } struct Caller { Caller(vector<string>& results) : m_res(results) { } void operator()(double x) { m_res.push_back(f(x, 1.0,2.0,3.0)); } private: vector<string>& m_res; }; int main() { vector<double> d; vector<string> r; d.push_back(1.0); d.push_back(2.0); Caller c(r); for_each(d.begin(), d.end(), c); } 
+3
source share

All Articles