![](/img/trans.png)
[英]Returned vector defined as "std::vector<<error-type>, std::allocator<<error-type>>>
[英]no suitable user-defined conversion from "lambda []()-><error-type>" to "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 << "}\n\n";
});
我收到一個錯誤:-
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
你能在這方面幫助我嗎
問題是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 << "}\n\n";
//----vv---->note the brackets for calling
})();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.