簡體   English   中英

使用迭代器替換向量中的對象

[英]Replace object in vector using iterator

這是我的對象類:

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; }

簡化的現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM