I have a vector of structs and I want to remove an element from the vector with specific values.I know how it can be done for for example a vector of int values using erase remove, but now sure how to do it for a vector of structs:
#include <algorithm>
#include <string>
#include <iostream>
using namespace std;
struct file_line{
string pcounter;
int optype;
};
int main() {
vector<file_line> v = {file_line{"aa",1}, file_line{"bb", 2}, file_line{"cc", 5}, file_line{"ddd", 12}};
v.erase(remove(v.begin(),v.end(),file_line{"cc",5} ), v.end());
return 0;
}
Here is the error that I receive:
/usr/include/c++/7/bits/predefined_ops.h:241:17: error: no match for ‘operator==’ (operand types are ‘file_line’ and ‘const file_line’)
{ return *__it == _M_value; }
As the error message says, the compiler doesn't know how to compare two file_line
objects. You can provide this comparison yourself by writing:
bool operator==(file_line const & a,file_line const & b)
{
return a.pcounter == b.pcounter and a.optype == b.optype;
}
Here's a demo.