std :: find对象指针的向量 [英] std::find on a vector of object pointers
问题描述
我有一个类 A
,其中一个成员是另一个类的对象指针的向量 B
class A
{
std :: vector< B *> m_member_A
现在我要执行 std :: find
在 m_member_A
。
例如
if(std :: find(m_member_A.begin(),m_member_A.end(),B_obj *)!= m_member_A.end())
std :: find对这样的向量没有意义。如何实现这样的功能?
如果它是一个B(不是指针)对象的向量,它会如何改变?
<如果你想通过指针而不是给定的指针找到一个值指针,你可以使用
std :: find_if > code>与一个合适的函子: struct Foo
{
int i;
};
bool operator ==(const Foo& lhs,const Foo& rhs){return lhs.i == rhs.i; }
std :: vector< Foo *> v = ....
Foo f {42};
std :: find_if(v.begin(),v.end(),[& f](const Foo * p){return * p == f;});
I have a class A
with a member which is a vector of object pointers of another class B
class A
{
std::vector<B*> m_member_A
Now I want to perform a std::find
on m_member_A
.
E.g.
if(std::find(m_member_A.begin(), m_member_A.end(), B_obj*) != m_member_A.end())
std::find doesn't make sense on such a vector. How do I achieve such a functionality?
How would it change if it were a vector of objects of B (not pointer)?
解决方案 If you want to find a value pointer at by the pointer, instead of a given pointer, you can use std::find_if
with a suitable functor:
struct Foo
{
int i;
};
bool operator==(const Foo& lhs, const Foo& rhs) { return lhs.i == rhs.i; }
std::vector<Foo*> v = ....;
Foo f{42};
std::find_if(v.begin(), v.end(), [&f](const Foo* p) { return *p == f; });
这篇关于std :: find对象指针的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!