[英]Can't I get a pointer as a parameter of STL predicate?
How can I get a pointer?我怎样才能得到一个指针?
I want to put a pointer as a parameter to the lambda expression you see!我想把一个指针作为参数指向你看到的 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;
The problem is that there is no implicit constructor for the class template std::unique_ptr that accepts an object of the template argument type.问题是 class 模板 std::unique_ptr 没有隐式构造函数,它接受模板参数类型的 object。
So this loop所以这个循环
for (int i = 0; i < 100; ++i)
{
arr.emplace_back(i);
}
is incorrect.是不正确的。
Also this statement还有这个说法
cout << *p << endl;
is also incorrect.也是不正确的。 Instead write而是写
cout << **p << endl;
It seems you mean the following看来你的意思如下
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;
The problem is not the lambda, it is how you construct elements in your vector.问题不在于 lambda,而在于您如何在向量中构造元素。 This is how you want to do it:这就是你想要的方式:
for (int i = 0; i != 100; ++i) {
arr.emplace_back( std::make_unique<int>( i ) );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.