std::find on a vector of object pointers

蹲街弑〆低调 提交于 2019-12-02 05:28:23

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; });

Vector works perfectly fine with std::find

auto result = std::find(m_member_A.begin(), m_member_A.end(), itemToFind);
if (result != m_member_A.end()) {
  // found it!
}

Or if you need to dereference the pointer:

auto result = std::find_if(m_member_A.begin(), m_member_A.end(), 
  [] (B* item) { 
    if (item == nullptr) return false; // may want to do something else here
    return *item == someValue;
  });
if (result != m_member_A.end()) {
  // found it!
}

Demo: http://ideone.com/jKCrG5

If you want to compare values instead of comparing pointers, you might want to use std::find_if instead:

bool IsFoo (B* _item) {
    bool result = false;

    if ( _item != nullptr && _item->value == 1 ) //Whatever is your criteria
        result = true; 

    return result;
}

std::vector<B*> m_member_A;
B* instance = std::find_if (m_member_A.begin(), m_member_A.end(), IsFoo);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!