c – 如何在函数内定义仿函数

前端之家收集整理的这篇文章主要介绍了c – 如何在函数内定义仿函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有时,我需要一些functor-helper来操作列表.我尽量将范围保持在本地范围内.
  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. struct Square
  8. {
  9. int operator()(int x)
  10. {
  11. return x*x;
  12. }
  13. };
  14.  
  15. int a[5] = {0,1,2,3,4};
  16. int b[5];
  17.  
  18. transform(a,a+5,b,Square());
  19.  
  20. for(int i=0; i<5; i++)
  21. cout<<a[i]<<" "<<b[i]<<endl;
  22. }
  1. hello.cpp: In function int main()’:
  2. hello.cpp:18:34: error: no matching function for call to transform(int [5],int*,int [5],main()::Square)’

如果我将Square移出main(),那没关系.

解决方法

你做不了.但是,在某些情况下,您可以使用boost :: bind或boost :: lambda库来构建仿函数,而无需声明外部结构.此外,如果您有一个最新的编译器(如gcc版本4.5),您可以启用新的C 0x功能,允许您使用lambda表达式,允许这样的语法:

transform(a,a 5,[](int x) – > int {return x * x;});

猜你在找的C&C++相关文章