I already know how to make a recursive lambda function that take one argument like calculating factorial of a number, but I try to make a recursive power function using lambda (as a practice), but taking 2 arguments in the function caused errors
this the code :
std::function <int(int)> power = [&](int a, int n)
{
return (n<=1) ? a : a*power(a, n-1);
};
this line return (n<=1) ? a : a*power(a, n-1);
gives these errors :
error: no match for call to '(std::function<int(int)>) (int&, int)' note: candidate: _Res std::function<_Res(_ArgTypes ...)>::operator()(_ArgTypes ...) const [with _Res = int; _ArgTypes = {int}] note: candidate expects 1 argument, 2 provided
You'll have to use
std::function <int(int, int)> power = [&](int a, int n) { ... }
for the function to work with two arguments.
n = 0
correctly.Use of
return (n <= 1) ? a : a*power(a, n-1);
is not right. You will get back a
when the function is called with n = 0
.
Use
return (n == 0) ? 1 : a*power(a, n-1);
unsigned int
for n
.std::function <int(int, unsigned int)> power = [&](int a, unsigned int n) { ... }
Then, you won't have to worry about the function getting called with negative values for n
.
std::function <int(int, unsigned int)> power = [&](int a, unsigned int n)
{
return (n == 0) ? 1 : a*power(a, n-1);
};