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) {}
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!
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.
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
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)