Search code examples
c++stlstdbind

The use of std::bind with a binary operation function in C++


I am trying to learn how the std::bind works. I wrote the following:

#include <iostream>
#include <algorithm>
#include <functional>


using namespace std::placeholders;

int fun2(int i,int j)
{
   return i+j;
}


int fun(int i)
{
  return i;
}

int main()
{
 std::vector<int> v9={1,2,3,4,5,6,6,7};
 std::transform(v9.begin(),v9.end(),v9.begin(),[](int i){return i;}); //works
 std::transform(v9.begin(),v9.end(),v9.begin(),fun); //works
 std::transform(v9.begin(),v9.end(),v9.begin(),std::bind(fun,_1)); //works
 std::transform(v9.begin(),v9.end(),v9.begin(),std::bind(fun2,_1,_2)); //does not work
}

std::transform also accepts binary operation functions. So I tried to wrote fun2 and use std::bind (last line of the main) but it doesn't work. Can someone give me any example how std::bind use placeholders (2,3 or more)?


Solution

  • The overload of std::transform that takes a binary functor takes four iterators, not three, since it operates on two input ranges, and not one. For example:

    #include <iostream>
    #include <algorithm>
    #include <functional>
    #include <iterator>
    
    int fun2(int i,int j)
    {
       return i+j;
    }
    
    int main()
    {
      using namespace std::placeholders;
      std::vector<int> v1={1,2,3,4,5,6,6,7};
      std::vector<int> v2;
      std::transform(v1.begin(), v1.end(), v1.begin(), 
                     std::back_inserter(v2), std::bind(fun2,_1,_2));
      for (const auto& i : v2)
        std::cout << i << " ";
      std::cout << std::endl;
    }
    

    Of course, in real life you wouldn't use std::bind here.