Your question isn't well-defined, but I will provide you with two answers. I am assuming here based on your code that obj
is not a pointer, which means that we are comparing an object to pointers to objects. This requires a custom functor.
The first answer is how to remove all elements of the vector where the value of the pointed-to element is equal to obj
. This assumes that there is an operator==
that can be applied to MyClass
objects.
pVector.erase(std::remove_if(pVector.begin(), pVector.end(),
[&obj](MyClass * i) { return i && (*i == obj); }));
The second will remove at most one element, if it is found:
auto e = std::find(pVector.begin(), pVector.end(),
[&obj](MyClass * i) { return i && (*i == obj); });
if (e != pVector.end()) {
pVector.erase(e);
}
The lambda syntax requires C++11. If you don't have access to C++11 then you will have to build a functor by hand:
template <typename T>
class pointer_is_equal_to_object
{
public:
explicit pointer_is_equal_to_object(T const &);
bool operator()(T const *) const;
private:
T const & value;
}
template <typename T>
pointer_is_equal_to_object<T>::pointer_is_equal_to_object(T const & v) : value(v) {}
template <typename T>
bool pointer_is_equal_to_object<T>::operator()(T const * p) const
{
return p && (*p == value);
}
Then, for example, you could use:
pVector.erase(std::remove_if(pVector.begin(), pVector.end(),
pointer_is_equal_to_object<MyClass>(obj)));
Note that this complexity goes away if you stop using pointers and just use std::vector<MyClass>
. Then your operator==
can be applied directly and you can just do:
pVector.erase(std::remove(pVector.begin(), pVector.end(), obj));