Reputation: 356
I would like to remove an object from a stl vector if it is present.
class test
{
vector<Objects> myvector;
public:
test();
removeTest(Objects);
}
test::removeTest(Objects aObject)
{
myvector.erase(remove(myvector.begin(), myvector.end(), aTest),myvector.end());
}
However, whenever I try to compile this, I get the following error:
no match for 'operator=='
This only occurs if I use an iterator through a vector of objects of type 'Objects'. I can get it to work for the case of looking for an integer then removing this.
Anyone know why I am getting these errors? And am I using the correct method to remove an object from a stl vector of objects by value?
Upvotes: 0
Views: 923
Reputation: 302767
no match for 'operator=='
Error says it all. You need to provide an equality comparison for your Object
class, std::remove
can't otherwise know how to compare your objects to determine which ones need to be removed.
For example:
struct Object {
int i;
std::string s;
bool operator==(const Object& rhs) const {
return i == rhs.i && s == rhs.s;
}
};
It worked for integers because equality comparison between integers is built-in. Not so for user-defined types.
With that, this:
void test::removeTest(const Object& aObject)
// ^^^^ ^^^^^^^^^^^^^
{
myvector.erase(
remove(myvector.begin(), myvector.end(), aObject),
// ^^^^^^^
myvector.end()
);
}
Should do exactly what you want. Note that you were missing a return type for removeTest
(I'm assuming you want void
) and you should take the object you want to remove by reference-to-const to avoid the unnecessary copy.
Upvotes: 1