开发者

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

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

vector&l开发者_如何转开发t;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.)


Are you missing the comparison operator?

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

        ... Other stuff
};


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜