I've just tried to code the Binder2nd, almost same as standard code provided in functional...... please point out the mistakes........ and suggest me guidelines to write effective code..........

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
 
using namespace std;

 
template <class _Fn> 
class Binder2: public unary_function
  <typename _Fn::first_argument_type,
                typename _Fn::result_type> 
{
protected:
typedef typename  _Fn::second_argument_type sArg_;
sArg_& secArg_;
 _Fn& fn_;
public:
Binder2(_Fn const& fn,typename _Fn::second_argument_type const& sArg)
:fn_(fn),secArg_(sArg){}
typename _Fn::result_type operator()(typename _Fn::first_argument_type& arg)
{
return fn_(arg,secArg_);
}
};
template<class _Fn,class _Arg> 
inline Binder2<_Fn> bind_(_Fn const& fn,_Arg const& arg)
{
return Binder2<_Fn>(fn,arg);
}
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
//this should print 5 10 15 20 25...... don't know why :S
std::transform(v.begin(),v.end(),v.begin(),std::ostream_iterator<int>(cout," "),bind_(std::multiplies<int>(), 5));
cout<<"\n";

cin.get();
 
return 0;
}

Help me in finding the error...... the error is @

bind_(std::multiplies<int>(),5)

term doesn't evaluate to a funciton taking 2 arguments :S

First of all, it looks like you've got the wrong overloaded version of std::transform. Namely, you're using the one that takes a binary function as its last argument, while you want it to take an unary function. You could do:

std::transform(v.begin(),v.end(),std::ostream_iterator<int>(cout," "),std::bind2nd(std::multiplies<int>(), 5));

This would give you the output you expect.

This article has been dead for over six months. Start a new discussion instead.