【问题标题】:Removing element from vector : Invalid operands to binary expression从向量中删除元素:二进制表达式的操作数无效
【发布时间】:2017-02-21 19:37:27
【问题描述】:

我正在尝试从向量中删除特定元素,但是当我使用擦除(删除)函数时,我收到此错误:

[...]/v1/algorithm:2139:24: 二进制表达式的操作数无效('Component' 和 'const Component')

我搜索了一个解决方案,在类内和类外定义了 == 运算符,但我找不到它为什么不起作用。

代码如下:

void OGWindow::deleteSquare( Component *squPtr )
{
    cout << "Deleting component " << squPtr->getIndex() << endl;
    compVector.erase(std::remove(compVector.begin(), compVector.end(), *squPtr), compVector.end());
}

运算符 == :

bool Component::operator==(Component& c){
    return this->getIndex() == c.getIndex();
}

分量索引与向量无关。

谢谢。

编辑:此运算符重载有效:

bool Component::operator==(const Component& c) const{
    return this->index == c.index;
}

【问题讨论】:

  • compVector 的定义是什么?
  • @Ap31 std::vector compVector;当我注释掉擦除行时,它会编译并且 cout 会打印出好的值。

标签: c++ vector


【解决方案1】:

std::remove 需要一个 const 引用作为比较的值。尝试在operator== 中引入一些const 修饰符:

bool Component::operator==(const Component& c) const

当然,这反过来也要求Component::getIndex() 也是const,所以请做好准备。

如果您不想将 operator== 设为 const,则始终可以使用 std::remove_if 而不是 std::remove 并使用自定义谓词 - 它甚至可以保存非 const 值并调用您喜欢的任何方法.

一般来说,如果可以使用const,通常是个好主意。

【讨论】:

  • 谢谢,它成功了 :) 我用修改后的代码编辑了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-03
  • 2016-02-11
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
相关资源
最近更新 更多