有时,我需要一些functor-helper来操作列表.我尽量将范围保持在本地范围内.
#include <iostream> #include <algorithm> using namespace std; int main() { struct Square { int operator()(int x) { return x*x; } }; int a[5] = {0,1,2,3,4}; int b[5]; transform(a,a+5,b,Square()); for(int i=0; i<5; i++) cout<<a[i]<<" "<<b[i]<<endl; }
hello.cpp: In function ‘int main()’: 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;});