Đôi khi, tôi cần một số trình trợ giúp hàm functor để thao tác danh sách. Tôi cố gắng giữ phạm vi địa phương càng tốt.cách xác định hàm functor bên trong hàm
#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)’
Nếu tôi chuyển Square
ra khỏi main()
, đó là ok.
[Xem câu hỏi này] (http://stackoverflow.com/questions/6880077/why-does-this-stdsort-predicate-fail-when-the-class-is-inside-main). – hammar
Hmm ... Tôi đã sao chép mã từ câu hỏi và thử nó trên VS2010, và nó hoạt động tốt ...: - \. – TCS