删除矢量中的特定值
我遇到了一个错误列表,当我试图执行此擦除功能从我的矢量中删除'2'时。我不确定问题在哪里。帮助将不胜感激!删除矢量中的特定值
STRUCT明特
struct MyInt
{
friend ostream &operator<<(ostream &printout, const MyInt &Qn)
{
printout<< Qn.value << endl;
return printout;
}
int value;
MyInt (int value) : value (value) {}
};
STRUCT的MyStuff
struct MyStuff
{
std::vector<MyInt> values;
MyStuff() : values()
{ }
};
MAIN
int main()
{
MyStuff mystuff1,mystuff2;
for (int x = 0; x < 5; ++x)
{
mystuff2.values.push_back (MyInt (x));
}
vector<MyInt>::iterator VITER;
mystuff2.values.push_back(10);
mystuff2.values.push_back(7);
//error points to the line below
mystuff2.values.erase(std::remove(mystuff2.values.begin(), mystuff2.values.end(), 2), mystuff2.values.end());
return 0;
}
错误消息
stl_algo.h:在函数 '_OutputIterator的std :: remove_copy(_InputInputIterator,_InputIterator,const_Tp &)[with_InputIterator = __gnu_cxx:__ normal_iterator>>,输出迭代= __ gnu_cxx :: __正常迭代>>,TP = INT]'
否匹配操作员==”
Erorr消息显示partciular线违反几乎stl_algo.h的线1267 线,1190,327,1263,208,212,216,220,228,232 ,236
您需要为MyInt
类别的==
运营商超载。
例如:
struct MyInt
{
friend ostream &operator<<(ostream &printout, const MyInt &Qn)
{
printout<< Qn.value << endl;
return printout;
}
// Overload the operator
bool operator==(const MyInt& rhs) const
{
return this->value == rhs.value;
}
int value;
MyInt (int value) : value (value) {}
};
该运算符应该是const。 –
@ BenjaminLindley修正了它。使它成为'const'的目的是什么? – 2012-05-13 18:08:42
所以你可以比较两个常量MyInt。 –
有两个问题。你看到的错误是告诉你,你还没有定义int和你的类型之间的平等比较。在你的结构,你应该定义一个平等运营商
bool operator==(int other) const
{
return value == other;
}
,当然在其他方向上定义一个全球运营商:
bool operator==(int value1, const MyInt& value2)
{
return value2 == value1;
}
“不匹配的==操作符”有什么不清楚呢?您需要定义一个'operator =='函数,以便您可以将myInt与整数进行比较。 – jrok
@jrok,这应该是一个答案。这真的很简单。 – chris