Question

I have the following method:

CalculateThreshold(std::vector<double> &data, int thres)
{
  // include functionality 
}

I then have a vector of vectors which I want to iterate through using the std::for_each and I have tried to use the following:

std::for_each(
   std::begin(results),
   std::end(results), 
   std::bind2nd(std::mem_fun(&CalculateThres), 1)); 

But I keep getting the error message:

note: candiditates are template std::mem_fun_t<_Ret, _Tp> std::mem_fun(_Ret (_Tp::*)())

Anyone have a suggestion to where I'm going wrong? To me, this should work!

Was it helpful?

Solution

Just use std::bind, there's no need for std::mem_fun (as explained in the comments).

std::for_each(
   std::begin(results),
   std::end(results), 
   std::bind(CalculateThres, std::placeholders::_1, 1)); 

Also, bind1st and bind2nd are deprecated, you should use bind instead. Similarly, mem_fun is deprecated too, its replacement is mem_fn.

OTHER TIPS

Let's look at what the compiler tells more closely, especially that part:

std::mem_fun_t<_Ret, _Tp> std::mem_fun(_Ret (_Tp::*)())

_Ret (_Tp::*)() represents a pointer to a member function. You tried to pass the free function CalculateThreshold so this won't work, the type does not match.

Also, std::mem_fun and std::bind2nd are deprecated in C++11.


You're using C++11, so you basically have three easy solutions :

  • Use the for range loop :

    for (auto && v : results)
        CalculateThreshold(v, 1);
    
  • Use std::bind with std::foreach :

    std::foreach(std::begin(results), std::end(results),
                 std::bind(CalculateThreshold, std::placeholders::_1, 1));
    
  • Use a lambda with std::foreach :

    std::foreach(std::begin(results), std::end(results),
                 [](std::vector<double> & data) { CalculateThreshold(data, 1); });
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top