Reputation: 3747
I am trying to erase an object from a vector in C++, but it is giving a strange (and long) error. I have written this :
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class foo
{
int a;
public:
foo(int _a):a(_a){}
};
int main() {
foo f1(5),f2(10);
vector<foo> vec = {f1,f2};
vec.erase(remove(vec.begin(),vec.end(),f1),vec.end()); // remove f1 (error)
return 0;
}
The exact error I get is here.
On the other hand, when I create a vector of int and then try to remove an integer from that vector, it works fine.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> vec = {5,10};
vec.erase(remove(vec.begin(),vec.end(),5),vec.end()); // works fine
return 0;
}
I am not sure why there is an error in first case.
Upvotes: 0
Views: 196
Reputation: 30489
For std::remove
your class foo
should contain operator ==
or you should explicitly pass a comparison function. For standard types (int
for example), comparison function is defined by language and thus it compiles without an error.
One example for operator ==
can be:
class foo
{
...
bool operator ==(const foo &t) const { return t.a == a; }
};
Upvotes: 5