asv*_*asv 3 c++ function vector
This code is not correct:
std::vector<int (*)(int)> fv;
for (int i=0; i<10; i++)
{
auto g = [i](int n) -> int
{
return n+i;
};
fv.push_back(&g);
}
Run Code Online (Sandbox Code Playgroud)
because lambda functions is not of type int (*)(int)
but is an object.
My question is: what type I must put in vector<...>
?
您可以使用库类型std::function
。
例如:
#include <vector>
#include <functional>
void foo() {
std::vector<std::function<int(int)>> fv;
for (int i = 0; i < 10; ++i) {
fv.emplace_back([i](int n) {
return n + i;
});
}
}
Run Code Online (Sandbox Code Playgroud)