仿函數經驗總結

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);
}

這裏不要求傳入的函數必須有返回值

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