![](/img/trans.png)
[英]Unable to use std::function as parameter type (need function pointer version) would rather template like the STL but then it can't deduce arguments
[英]Can't I get a pointer as a parameter of STL predicate?
我怎樣才能得到一個指針?
我想把一個指針作為參數指向你看到的 lambda 表達式!
vector<unique_ptr<int>> arr{};
for (int i = 0; i < 100; ++i) {
arr.emplace_back(i);
}
auto p = find_if(arr.begin(), arr.end(),
[](const unique_ptr<int>& a) // error
{ return *a == 10; });
cout << *p << endl;
問題是 class 模板 std::unique_ptr 沒有隱式構造函數,它接受模板參數類型的 object。
所以這個循環
for (int i = 0; i < 100; ++i)
{
arr.emplace_back(i);
}
是不正確的。
還有這個說法
cout << *p << endl;
也是不正確的。 而是寫
cout << **p << endl;
看來你的意思如下
for (int i = 0; i < 100; ++i)
{
arr.emplace_back( make_unique<int>( i ) );
}
auto p = find_if(arr.begin(), arr.end(), [](const unique_ptr<int>& a) // error
{
return *a == 10;
});
if ( p != arr.end() ) cout << **p << endl;
問題不在於 lambda,而在於您如何在向量中構造元素。 這就是你想要的方式:
for (int i = 0; i != 100; ++i) {
arr.emplace_back( std::make_unique<int>( i ) );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.