修正下我自个模仿的STL
#include <iostream>#include <string>#include <vector>#include <algorithm > using namespace std;template<class _Arg1,class _Result>struct unary_function{ typedef _Arg1 argument_type; typedef _Result result_type;};template <class _Arg1, class _Arg2, class _Result>struct binary_function { typedef _Arg1 first_argument_type; typedef _Arg2 second_argument_type; typedef _Result result_type;};template<class _Tp>struct plus:public binary_function<_Tp,_Tp,_Tp>{ _Tp operator() ( const _Tp &_x,const _Tp& _y) const { cout<<"_x="<<_x<<","<<"_y"<<_y<<endl; return _x+_y; }};template <class _Tp>struct binder2nd :public unary_function<_Tp::first_argument_type,_Tp::result_type>{ _Tp op; _Tp::second_argument_type value; binder2nd(const _Tp& _X,const _Tp::second_argument_type& _Y):op(_X),value(_Y){}; result_type operator()(const argument_type& _X) const { return op(_X,value); }};int main(){ int ia[5]={0,1,2,3,4}; vector<int> m_vector; m_vector.insert(m_vector.begin(),ia,ia+5); copy(m_vector.begin(),m_vector.end(),ostream_iterator<int>(cout," ")); for_each(m_vector.begin(),m_vector.end(),binder2nd<plus<int> >(plus<int>(),4)); copy(m_vector.begin(),m_vector.end(),ostream_iterator<int>(cout," "));}struct binder2nd :public unary_function<typename _Tp::first_argument_type,typename _Tp::result_type>
[解决办法]
用transform可以加4
transform(m_vector.begin(), m_vector.end(), m_vector.begin(), binder2nd<plus<int>>(plus<int>(),4));
[解决办法]
楼主是想将结果值加4?
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
template <typename _Arg1,typename _Result>
class unary_function{
public:
typedef _Arg1 argument_type;
typedef _Result result_type;
};
template <typename _Arg1, typename _Arg2, typename _Result>
class binary_function {
public:
typedef _Arg1 first_argument_type;
typedef _Arg2 second_argument_type;
typedef _Result result_type;
};
template <typename _Tp>
class plus : public binary_function <_Tp,_Tp,_Tp>
{
public:
_Tp operator() ( _Tp &_x,const _Tp& _y) const
{
cout < <"_x=" < <_x < <"," < <"_y=" < <_y < <endl;
return _x += _y;
}
};
template <typename _Tp>
class binder2nd : public unary_function <_Tp::first_argument_type,_Tp::result_type>
{
public:
_Tp op;
_Tp::second_argument_type value;
binder2nd(_Tp& _X, _Tp::second_argument_type& _Y):op(_X),value(_Y){};
result_type operator()(argument_type& _X) const
{
return op(_X,value);
}
};
int main(void)
{
int ia[5]={0,1,2,3,4};
int dest[5];
int addition = 4;
vector <int> m_vector;
m_vector.insert(m_vector.begin(),ia,ia+5);
copy(m_vector.begin(),m_vector.end(),dest);
plus <int> p;
binder2nd < plus <int> > b(p,addition);
for_each(m_vector.begin(),m_vector.end(), b);
copy(m_vector.begin(),m_vector.end(), dest);
return 0;
}
template <class _Fn2, class _Ty>inline binder2nd<_Fn2> bind2nd( const _Fn2& _Func, const _Ty& _Right ){ typename _Fn2::second_argument_type _Val( _Right ); return ( binder2nd<_Fn2>( _Func, _Val ) );}