3

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

1
  • Can you not supply a default for int* d? Commented Feb 20, 2014 at 9:49

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Why use std::bind, when lambda is a lot simpler. (In pre-C++11, this would be a good use of boost::bind.)
@JamesKanze Didn't think of it until I'd already written my answer. And that's why I upvoted the answer from Alexander. :)
The semantics of bind are clearer than that of a lambda function, in my opinion.
6

try to use a lambda-function:

std::for_each (mydata.begin(), mydata.end(), [&](double d)
{
  train(d, net);
});

1 Comment

Why take net by reference? I'd do [net](double d){ train(d, net); } - just copy the pointer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.