首页 > 代码库 > 仿函数和函数配接器

仿函数和函数配接器

////  main.cpp//  function_adaptor////  Created by IDM-PKU on 14-9-3.//  Copyright (c) 2014年 PKU. All rights reserved.//#include <iostream>#include <set>#include <deque>#include <algorithm>#include "print.hpp"using namespace std;int main(int argc, const char * argv[]){    set<int,greater<int> > coll1;    deque<int> coll2;    for (int i=1; i<=9; ++i) {        coll1.insert(i);    }    PRINT_ELEMENTS(coll1,"initialized: ");    transform(coll1.begin(), coll1.end(),back_inserter(coll2),bind2nd(multiplies<int>(), 10));    PRINT_ELEMENTS(coll2);    replace_if(coll2.begin(), coll2.end(), bind2nd(equal_to<int>(), 70), 42);    PRINT_ELEMENTS(coll2,"replace: ");    coll2.erase(remove_if(coll2.begin(), coll2.end(), bind2nd(less<int>(), 50)), coll2.end());    PRINT_ELEMENTS(coll2,"removed: ");    return 0;}

  

////  print.hpp//  function_adaptor////  Created by IDM-PKUSZ on 14-9-3.//  Copyright (c) 2014年 PKU. All rights reserved.//#ifndef function_adaptor_print_hpp#define function_adaptor_print_hpp#include <iostream>template <class T>inline void PRINT_ELEMENTS(const T & coll, const char * optcstr=""){    typename T::const_iterator pos;    std::cout << optcstr;    for(pos=coll.begin();pos!=coll.end();++pos)        std::cout << *pos << ‘ ‘;    std::cout << std::endl;}#endif

  透过一些特殊的函数配接器,你可以将预先定义的仿函数和其它数值组合在一起。

下面是在Mac OS下的运行结果:

仿函数和函数配接器