Nick Heiner
Nick Heiner

Reputation: 122442

C++: Difficulty with removing an item from a vector

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.)

Upvotes: 0

Views: 197

Answers (3)

Robert Cooper
Robert Cooper

Reputation: 1270

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.

Upvotes: 0

Loki Astari
Loki Astari

Reputation: 264381

Are you missing the comparison operator?

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

        ... Other stuff
};

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308158

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());

Upvotes: 0

Related Questions