删除向量中的特定值

Removing a specific value in vector

本文关键字:向量 删除      更新时间:2023-10-16

当我尝试执行此擦除函数以从向量中删除"2"时,我遇到了一系列错误。我不确定问题出在哪里。帮助将不胜感激!

结构 MyInt

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
{
  std::vector<MyInt> values;
  MyStuff () : values ()
  { }
};

主要

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>>, OutputIterator = __ gnu_cxx::__normal 迭代器>>, Tp = int]'

运算符不匹配=='

Erorr消息显示分词线路实际上违反了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) {}
};

有两个问题。您看到的错误告诉您尚未定义 int 和类型之间的相等比较。在结构中,应定义一个相等运算符

bool operator==(int other) const
{
    return value == other;
}

当然,在另一个方向上定义一个全局运算符:

bool operator==(int value1, const MyInt& value2)
{
    return value2 == value1;
}