【问题标题】:Replace object in vector using iterator使用迭代器替换向量中的对象
【发布时间】:2019-04-03 22:01:21
【问题描述】:

这是我的对象类:

class person
{
public:

    int id;
    Rect rect;
};

主要是,我正在遍历persons 的向量,当我找到匹配项时,我想将rect 更新为一些新的rect,甚至替换整个新对象person

Rect mr = boundingRect(Mat(*itc));
person per;
vector <person> persons;
vector <person>::iterator i;

i = persons.begin();
while (i != persons.end()) {
    if ((mr & i->rect).area() > 0) {
        rectangle(frame, mr, CV_RGB(255, 0, 0));
        putText(frame, std::to_string(i->id).c_str(), mr.br(),
            FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 255));

        replace(persons.begin(), persons.end(), i->rect, mr); // this line causes error
        break;
    } else {
      ...
    }

我在注释标记的行中遇到的错误是:

Error   C2678   binary '==': no operator found which takes a left-hand operand of type 'person' (or there is no acceptable conversion)

还有这个:

Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'const _Ty' (or there is no acceptable conversion)   

我尝试erase 对象并添加一个新对象,但我仍然遇到同样的错误。我已经阅读了C++ Remove object from vector,但我不确定这是否是我的问题,而且我没有使用 C++11,所以这些解决方案对我不起作用。

在进行比较时,迭代器和我的person 对象是否存在问题?我认为是但不知道如何解决它。

【问题讨论】:

  • 你不能i-&gt;rect = mr;吗?
  • 我可以,但我还需要使用 replaceremove 对象...并且两者都会出现此错误...我的意思是您建议的解决方法,但我是寻找解决方案如何以正确的方式修复它。
  • 如果你只是想改变vector内当前person对象的rect成员,并保持相同的顺序,你不需要做任何删除或替换。只需i-&gt;rect = mr; 就可以做到这一点,因为*i 是向量中的对象,而不是它的副本。如果这不是您想要的,请编辑帖子以更准确地描述您要完成的任务。
  • @mrRobot 我没有投反对票,但请看Why isn't providing feedback mandatory on downvotes, and why are ideas suggesting such shot down? 反对意见的评论不是强制性的,原因有很多。不发表评论不是恶意行为。

标签: c++ vector iterator


【解决方案1】:

如果您想比较person 类型的对象和Rect 类型的对象(这就是您对replace 的调用所暗示的),那么您必须在您的@ 中提供适当的比较运算符来执行此操作987654326@类,像这样:

bool operator== (const Rect &r) const { ... }

同样,您需要一个带有签名(和可能的实现)的赋值运算符,如下所示:

person& operator= (const Rect &r) { rect = r; return *this; }

Simplified live demo

【讨论】:

  • 我对@9​​87654329@ 的调用不是暗示我将person-&gt;rectrect 进行比较吗?这不一样吗?
  • 不,它会尝试将 personrect 进行比较,因此会遇到困难,但知道这应该有助于您编写 operator== 函数。
  • 如果我想erase迭代器指向的对象,我该怎么做?因为我已经尝试过了,我得到了同样的错误。
  • 请将其作为新问题发布,并显示您的代码。尝试发布minimal reproducible example
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-13
  • 1970-01-01
  • 2021-06-08
  • 2017-08-29
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多