使用迭代器替换矢量中的对象

Replace object in vector using iterator

本文关键字:对象 迭代器 替换      更新时间:2023-10-16

这是我的对象类:

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++从矢量中删除对象,但我不确定这是否是我的问题,我没有使用 C++11,所以这些解决方案对我不起作用。

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

如果要将类型为 person 的对象与类型 Rect 的对象进行比较(这是对 replace 的调用所暗示的(,则必须在 Person 类中提供适当的比较运算符来执行此操作,如下所示:

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

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

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

简化的现场演示