首页 > 解决方案 > 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);

}

标签: c++lambda

解决方案


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);

推荐阅读