I found the functor can be used to simulate defining a function within a function like this
using namespace std;
int main(int argc, char* argv[])
{
struct MYINC {
int operator()(int a) { return a+1; }
} myinc;
vector<int> vec;
for (int i = 0; i < 10; i++) vec.push_back(myinc(i));
return 0;
}
But If I passed it to an outside function, such as std::transform like the following example, I've got a compiling error saying error: no matching function for call to ‘transform(std::vector<int>::iterator, std::vector<int>::iterator, std::vector<int>::iterator, main(int, char**)::MYINC&)’
using namespace std;
int main(int argc, char* argv[])
{
struct MYINC{
int operator()(int a) { return a+1; }
} myinc;
vector<int> vec;
for (int i = 0; i < 10; i++) vec.push_back(i);
transform(vec.begin(), vec.end(), vec.begin(), myinc);
return 0;
}
So I put the definition outside the main function and all is OK now.
using namespace std;
struct MYINC{
int operator()(int a) { return a+1; }
} myinc;
int main(int argc, char* argv[])
{
vector<int> vec;
for (int i = 0; i < 10; i++) vec.push_back(i);
transform(vec.begin(), vec.end(), vec.begin(), myinc);
return 0;
}