仿函数经验总结
来源:互联网 发布:睡眠软件哪个好 编辑:程序博客网 时间:2024/05/09 18:22
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);}
这里不要求传入的函数必须有返回值
0 0
- 仿函数经验总结
- 仿作4399 经验总结
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- 仿函数
- mysql用户管理
- java 利用 poi 生成 Excel文件与spring使用文件流形式下载文件
- 飞机大战-BasicView
- Struts2 注解中跳转 action
- 【小萝莉说Crash】第一期:Unrecognized selector sent to instance xxxx
- 仿函数经验总结
- 网页元素居中攻略记_(2)元素垂直居中
- Zend Studio 10 破解
- Error android.text.StaticLayout.calculateEllipsis(StaticLayout.java:783)
- Python 排序
- opencv for android 教程
- 微信公众号开发:用从微信服务器下载图片资源
- poj 3522 Slim Span
- hdu3397 Sequence operation