昨天我得同事TY遇到一个问题,问题抽象如下:
编译的时候提示:
for_each(v.begin(), v.end(), p()); 这一句中类p中运算()不匹配。
而后qq群中的海东青给出了一个版本:
问题解决,编译也通过。但是就是不明白为什么做样做就可以。
后来同时qq群众的tary发来一段文字,现在附录在下:
for_each
template<class InIt, class Fun>
Fun for_each(InIt first, InIt last, Fun f);
The template function evaluates f(*(first + N)) once for each N in the range [0, last - first). It then returns f. The call f(*(first + N)) must not alter *(first + N).
See the related sample program.
刚开始不明白他的意思。后来想想了,才明白作为for_each的函数的形参类型有特别的要求。
第一:必须为单参数;
第二:必须跟*iter的类型一致或者兼容。既它的形参不能是迭代器或者指针。只能是类型或者它的引用。
为了考证这一点,我到cpluplus网站去看了for_each的接口定义。
链接:http://www.cplusplus.com/reference/algorithm/for_each/ 1
最后附上一个程序验证这一点:
编译通过:
运行结构如下:
Hello, the world!
0 1 2 3 4 5 6 7 8 9
参考:
鸣谢:
海东青,tary,还有我的同事TY。