How can I get a pointer?
I want to put a pointer as a parameter to the lambda expression you see!
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.
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. This is how you want to do it:
for (int i = 0; i != 100; ++i) {
arr.emplace_back( std::make_unique<int>( i ) );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.