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


Question

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) {}
    bool operator==(const A& p) {
        return p._a == _a; 
    }

private: 
    string _a;
};

vector<A*> va;

va.push_back(new A("one"));
va.push_back(new A("two"));
va.push_back(new A("three"));

find(va.begin(), va.end(), new A("two"));

I want to find the second item pushed into the vector. But since vector is defined as a pointers collection, C++ does not use my overloaded operator, but uses implicit pointer comparison. What is the preferred C++-way of solutiono in this situation?

1
17
11/3/2008 3:25:13 PM

Accepted Answer

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.

17
11/3/2008 3:45:18 PM

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)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon