Reputation: 276
Suppose I have a method:
std::vector<double> minimize(double (*f)(const std::vector<double>& x))
that takes a function f(x) and finds x that minimizes it. Suppose I want to minimize a function g(x, a) (with respect to x) which also takes a parameter a as an argument:
double g(const std::vector<double>& x, const double a)
How can I do this (in c++11) using the method minimize if the value of a is known only at runtime?
Upvotes: 0
Views: 883
Reputation: 347
Use labda as Puppy suggested, but additinally update minimize
to be a function template. Using template parameter instead of std::function will dramatically speed up minimize
//somewhere in header file
template<class Function>
std::vector<double> minimize(const Function& f){
...
}
...
//in any place where minimize is visible
minimize([=](const std::vector<double>& x) { return g(x, a); });
Upvotes: 1
Reputation: 146930
You can easily use a lambda.
minimize([=](const std::vector<double>& x) { return g(x, a); });
This is assuming that you change your function to use std::function
instead of a function pointer. Function pointers are terribly limited and can't do anything interesting at all, like this, so it's best to forget they exist.
Upvotes: 4