views:

83

answers:

4

I'm trying to remove an element from a vector.

vector<Foo> vecFoo;

Foo f1;
Foo f2;
Foo f3;

vecFoo.push_back(f1);
vecFoo.push_back(f2);
vecFoo.push_back(f3);

Foo* pF1 = &f1;

vecFoo.erase(std::remove(vecFoo.begin(), vecFoo.end(), *pF1), vecFoo.end());

That last line produces a huge amount of C2784 errors. What am I doing wrong?

(Yes, this example is bit contrived, but the essence is that I've got a pointer to an element in the vector, and I want to remove that element.)

A: 

That example works at VC++08

Make sure to #include <vector> and #include <algorithm>

Also, the vector function pushBack doesn't exist. It should be push_back

BlaXpirit
A: 

You don't have a pointer to the element, because push_back makes a copy. You could fix that with Foo* pF1 = &vecFoo[0];

Assuming that was just a typo, you can get an iterator to the element very simply, since vector iterators are random access.

vector<Foo>::iterator i = vecFoo.begin() + (pF1 - &vecFoo.front());
Mark Ransom
Perhaps I'm missing something but you can very well compare f1 (or *pF1 as in the OP's example) with it's copy that's actually stored in std::vector as long as Foo has an comparison operator defined...
Eugen Constantin Dinca
@Eugen, no you're not missing anything, I was a bit confused by the structure of the question. I'm tempted to delete this answer, but I still think it might be useful; I don't know enough about the actual problem yet.
Mark Ransom
+2  A: 

Are you missing the comparison operator?

class Foo
{
    public:
        bool operator==(Foo const& rhs) const { return true;}

        ... Other stuff
};
Martin York
A: 

Have you overloaded Foo's operator==?

Does Foo have a non-trivial destructor, assignment operator, or copy constructor, but not all three? If you define one, you must define them all.

Even if you haven't overloaded the destructor, assignment operator, or copy constructor, one of you Foo's members have declared private its destructor or assignment operator or copy constructor.