有时,我需要一些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;
}
Run Code Online (Sandbox Code Playgroud)
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)’
Run Code Online (Sandbox Code Playgroud)
如果我搬出Square去main(),没关系.
你做不了.但是,在某些情况下,您可以使用boost::bind或boost::lambda库来构建仿函数,而无需声明外部结构.此外,如果你有一个最新的编译器(如gcc版本4.5),你可以启用新的C++ 0x功能,允许你使用lambda表达式,允许这样的语法:
transform(a, a+5, b, [](int x) -> int { return x*x; });