没有合适的用户定义从"lambda []()-><error-type>"到"const std::vector<int, std::allocator<int>&



我尝试实现lambda函数:-

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 << "}nn";  

});

我得到一个错误:-

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:Usersinsmitrsourcereposconsoleapplicationconsoleapplication.cpp 46  IntelliSense    
2.Severity  Code    Description Project File    Line    Source  Suppression State
Error (active)  E0079   expected a type specifier   consoleapplication  C:Usersinsmitrsourcereposconsoleapplicationconsoleapplication.cpp 47  IntelliSense

你能在这方面帮助我吗

问题是print接受vector<int>,但在调用print时,您传递了一个lambda,并且由于没有从lambda到向量的隐式转换,因此您得到了上述错误。

您不一定需要调用print,因为您只需调用lambda本身,如下所示。另一种方法是使print成为一个函数模板,这样它可以接受任何可调用对象,然后调用传递的可调用对象。

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 << "}nn";  
//----vv---->note the brackets for calling
})();
return 0;
}

演示

相关内容

  • 没有找到相关文章

最新更新