删除向量中的特定值

时间:2012-05-13 18:00:09

标签: c++ vector

当我尝试执行此擦除功能从我的向量中删除“2”时,我遇到了错误列表。我不确定问题出在哪里。非常感谢帮助!

STRUCT 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

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&amp;)[with_InputIterator = __gnu_cxx:__ normal_iterator&gt; &gt;,OutputIterator = __ gnu_cxx :: __ normal iterator&gt; &gt;,Tp = int]'

     

无法匹配运营商=='

Erorr消息显示,partciular线实际上违反了stl_algo.h的行 线1267,1190,327,1263,208,212,216,220,228,232,236

2 个答案:

答案 0 :(得分:2)

您需要为==课程的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) {}
};

答案 1 :(得分:1)

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

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

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

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