仿函数经验总结

transform

transform的行为

template <class InputIterator, class OutputIterator, class UnaryOperator>
  OutputIterator transform (InputIterator first1, InputIterator last1,
                            OutputIterator result, UnaryOperator op)
{
  while (first1 != last1) {
    *result = op(*first1);  // or: result=binary_op(*first1,*first2++);
    ++result; ++first1;
  }
  return result;
}

从第6行可以看到传入的仿函数必须有返回值
比如预先定义的仿函数negate:求相反数的

template <class T> struct negate {
  T operator() (const T& x) const {return -x;}
  typedef T argument_type;
  typedef T result_type;
};

下面是一个实例:把list里面的元素平方后输出

#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
using namespace std;

template <class T1, class T2>
inline void PRINTCOLL(const T1 &coll, const char * optcstr=" "){
    std::cout << optcstr;
    copy(coll.begin(), coll.end(),
        ostream_iterator<T2>(cout, " "));
    std::cout <<"\n";
}

template <class T>
class MySquare
{
    public:
        MySquare(){};
        T operator()(T & elem)const{
            return elem * elem;
        };
};

template <class T>
class MyMutiply
{
    public:
        MyMutiply(T val){};
        MyMutiply(){};
        T operator()(T & elem1, T& elem2)const{
            return elem1 * elem2;
        };
};

int main(){
    list<int> coll;
    list<int> coll2;

    for(int i = 0; i < 10 ; ++i){
        coll.push_back(i);
    }
    transform(coll.begin(), coll.end(),\
        coll.begin(), MySquare<int>());
    PRINTCOLL<list<int>, int>(coll);
    transform(coll.begin(), coll.end(),\
        coll.begin(), coll.begin(), MyMutiply<int>());
    PRINTCOLL<list<int>, int>(coll);

//  transform(coll.begin(), coll.end(),\
        back_inserter(coll2), \
        bind2nd(MyMutiply<int>(), 10));
    transform(coll.begin(), coll.end(),\
        back_inserter(coll2), \
        bind2nd(multiplies<int>(), 10));
    PRINTCOLL<list<int>, int>(coll2);
}

第50行报错,暂时没找到解决办法,等看了后面的章节再回过头来调试

for_each

for_each的行为

template<class InputIterator, class Function>
  Function for_each(InputIterator first, InputIterator last, Function fn)
{
  while (first!=last) {
    fn (*first);
    ++first;
  }
  return fn;      // or, since C++11: return move(fn);
}

这里不要求传入的函数必须有返回值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章