Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::for_each on call a function with multiple arguments

Tags:

c++

c++11

I did search, but the closest link , among those found, even doesn't match my problem. I have a std::vector<double> mydata array. I like to use for_each for that mydata array in calling a member function. That member function accepts two arguments. One is each element of mydata array and another one is a int* of another array. I do like

::std::for_each (mydata.begin(), mydata.end(), train(net));

That gives me a compilation error of train function does not take one argument. I know how to use for_each if there isn't int*.

My train function is

void train(double const & data, int* d){}

How can I make it work? Thanks

like image 684
batuman Avatar asked Jan 23 '26 22:01

batuman


2 Answers

If you have C++11 you can use std::bind:

using namespace std::placeholders;  // For `_1`

std::for_each (mydata.begin(), mydata.end(),
               std::bind(&MyClass::train, this, _1, net));

Here the member-function will be called with three arguments: The first is the this pointer, which is always a hidden first argument in all member functions. The second will be the first argument passed to the callable object created by std::bind, and the third argument is the net variable.

like image 166
Some programmer dude Avatar answered Jan 25 '26 11:01

Some programmer dude


try to use a lambda-function:

std::for_each (mydata.begin(), mydata.end(), [&](double d)
{
  train(d, net);
});
like image 25
Alexander Avatar answered Jan 25 '26 13:01

Alexander