std::find on a vector of object pointers

前端 未结 3 1589
旧时难觅i
旧时难觅i 2021-01-24 14:48

I have a class A with a member which is a vector of object pointers of another class B

class A
{
    std::vector m_member_A
<         


        
3条回答
  •  醉话见心
    2021-01-24 15:38

    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 v = ....;
    
    Foo f{42};
    
    std::find_if(v.begin(), v.end(), [&f](const Foo* p) { return *p == f; });
    

提交回复
热议问题