删除向量中的特定值
Removing a specific value in vector
当我尝试执行此擦除函数以从向量中删除"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;
}
相关文章:
- 迭代时从向量和内存中删除对象
- 如何在向量中删除 std::function<void()>?
- 移除和删除与向量中的条件匹配的指针
- 比较 2 个向量并从第二个向量中删除在第一个 - c++ 中找不到的元素
- 为什么通过 vector<reference_wrapper> 的元素删除引用的值<T>不会使向量无效?
- 如何在元组初始化向量中删除样板?
- 如何删除包含其他向量的向量?
- 从列表向量中删除无法按预期工作
- 从数组中删除非唯一值、保持顺序和不使用向量的最佳方法?
- 如何删除除 ArduinoSTL 的向量函数之外的所有函数
- 如何在具有特定条件的向量中删除所有元组?
- 删除指向抽象类的指针向量
- 从自定义数据类型向量中删除重复元素
- 防止我的向量在调用它的函数结束时被删除
- 从ints向量删除int的问题
- 使用find_if从向量删除所有偶数数字
- 崩溃,如果使用向量删除了一个嵌入式容器的destructor中删除char*成员
- 从向量删除重复元素
- 基元向量删除引发异常
- 如何使用指向每个元素的指针向量删除qcheckbox数组?