Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

no suitable user-defined conversion from "lambda []()-><error-type>" to "const std::vector<int, std::allocator<int>>"

Tags:

c++

I try to implement lambda function:-

    vector<int> numbers;
    int value = 0;

    cout << "Pushing back...\n";
    while (value >= 0) {
        cout << "Enter number: ";
        cin >> value;
        if (value >= 0)
            numbers.push_back(value);
    }
    print( [numbers]() ->  
    {

        cout << "Vector content: {  ";
        for (const int& num : numbers)
            cout << num << "  ";
        cout << "}\n\n";  


    });

I got an error:-

1.Severity  Code    Description Project File    Line    Source  Suppression State
Error (active)  E0312   no suitable user-defined conversion from "lambda []()-><error-type>" to "const std::vector<int, std::allocator<int>>" exists    consoleapplication  C:\Users\insmitr\source\repos\consoleapplication\consoleapplication.cpp 46  IntelliSense    

2.Severity  Code    Description Project File    Line    Source  Suppression State
Error (active)  E0079   expected a type specifier   consoleapplication  C:\Users\insmitr\source\repos\consoleapplication\consoleapplication.cpp 47  IntelliSense

Could you please help me in this regards

like image 433
Sangita Paul Avatar asked Sep 17 '26 12:09

Sangita Paul


1 Answers

The problem is that print accepts a vector<int> but while calling print you're passing a lambda and since there is no implicit conversion from the lambda to the vector, you get the mentioned error.

You don't necessarily need to call print as you can just call the lambda itself as shown below. Other way is to make print a function template so that it can accept any callable and then call the passed callable.

int main()
{
    std::vector<int> numbers;
    int value = 0;

    cout << "Pushing back...\n";
    while (value >= 0) {
        cout << "Enter number: ";
        cin >> value;
        if (value >= 0)
            numbers.push_back(value);
    }
//-------------------vvvv------>void added here
    ( [numbers]() -> void 
    {

        cout << "Vector content: {  ";
        for (const int& num : numbers)
            cout << num << "  ";
        cout << "}\n\n";  

//----vv---->note the brackets for calling
    })();
    return 0;
}

Demo

like image 87
Anoop Rana Avatar answered Sep 19 '26 02:09

Anoop Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!