[英]Find weak_ptr in vector
I am trying to find weak_ptr in vector. 我试图在向量中找到weak_ptr。 I am using lambda expression as a third parameter to find but I can't understand why this code is not compiled:
我使用lambda表达式作为查找的第三个参数,但我不明白为什么未编译此代码:
std::vector<std::weak_ptr<Car>> cars;
std::shared_ptr<Car> lambo = std::make_shared<Car>();
std::weak_ptr<Car> wPtr(lambo);
cars.emplace_back(lambo);
const auto pos = std::find(cars.begin(), cars.end(), [&wPtr](const std::weak_ptr<Car>& ptr1) {
return ptr1.lock() == wPtr.lock();
});
if (pos != cars.end())
cout << "Not found!" << endl;
Maybe someone could point me what I am doing wrong. 也许有人可以指出我做错了什么。 Thanks in advance.
提前致谢。
I'm sure you meant std::find_if
(which takes a predicate), not std::find
(which takes a value ). 我确定您的意思是
std::find_if
(带一个谓词),而不是std::find
(带一个值 )。
Also fixing your conditional at the end, and adding appropriate boilerplate, we get: 最后还修复您的条件,并添加适当的样板,我们得到:
#include <vector>
#include <memory>
#include <iostream>
#include <algorithm>
struct Car {};
int main()
{
std::vector<std::weak_ptr<Car>> cars;
std::shared_ptr<Car> lambo = std::make_shared<Car>();
std::weak_ptr<Car> wPtr(lambo);
cars.emplace_back(lambo);
const auto pos = std::find_if(cars.begin(), cars.end(), [&wPtr](const std::weak_ptr<Car>& ptr1) {
return ptr1.lock() == wPtr.lock();
});
if (pos == cars.end())
std::cout << "Not found!" << std::endl;
else
std::cout << "Found!" << std::endl;
}
// Output: Found!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.