How to use find algorithm with a vector of pointers to objects in c++?

后端 未结 4 2070
逝去的感伤
逝去的感伤 2021-02-07 07:04

I want to find in a vector of Object pointers for a matching object. Here\'s a sample code to illustrate my problem:

class A {
public:
    A(string a):_a(a) {}
          


        
相关标签:
4条回答
  • 2021-02-07 07:45

    You could also use Boost::Lambda:

    using namespace boost::lambda;
    find_if(va.begin(), va.end(), *_1 == A("two"));
    

    Of course, you should prefer to use shared_ptrs so you don't have to remember to delete!

    0 讨论(0)
  • 2021-02-07 07:54

    Use find_if with a functor:

    template <typename T>
    struct pointer_values_equal
    {
        const T* to_find;
    
        bool operator()(const T* other) const
        {
            return *to_find == *other;
        }
    };
    
    
    // usage:
    void test(const vector<A*>& va)
    {
        A* to_find = new A("two");
        pointer_values_equal<A> eq = { to_find };
        find_if(va.begin(), va.end(), eq);
        // don't forget to delete A!
    }
    

    Note: your operator== for A ought to be const, or, better still, write it as a non-member friend function.

    0 讨论(0)
  • 2021-02-07 07:57

    Try using find_if instead. It has a parameter for a predicate where you can decide exactly how to check wheter you found the right element.

    http://www.sgi.com/tech/stl/find_if.html

    0 讨论(0)
  • 2021-02-07 08:07

    Either use std::find_if and provide a suitable predicate yourself, see other answers for an example of this.

    Or as an alternative have a look at boost::ptr_vector, which provides transparent reference access to elements which are really stored as pointers (as an extra bonus, memory management is handled for you as well)

    0 讨论(0)
提交回复
热议问题