'error: no viable conversion from '(lambda at A.cpp:21:22)' to 'int'
What am I missing? Lambda declaration error. Marked in comment.
void solve() {
int charCount, time;
cin>> charCount >> time;
// Generating error: no viable conversion from
// '(lambda at A.cpp:21:22)' to 'int'
int rightDistance = [&](int i) {
return charCount - i -1;
};
rightDistance(10);
}
Solution 1:[1]
You're trying to initialize rightDistance
from the lambda itself. You should call the lambda as
int rightDistance = [&](int i)
{
return charCount - i -1;
} (42);
//^^^^
If you want to declare the lambda variable, then declare the type of rightDistance
with auto
instead of int
.
auto rightDistance = [&](int i)
{
return charCount - i -1;
};
rightDistance(10);
Solution 2:[2]
The statement [&] declares a lambda. You may imaging this like some not trivial object that can't be assigned to int. Let the compiler to deduce the type of this object. Later you can use this object as a function call.
auto rightDistance = [&](int i)
{
return charCount - i -1;
};
rightDistance(10);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | 273K |