简体   繁体   中英

Replace object in vector using iterator

This is my object class:

class person
{
public:

    int id;
    Rect rect;
};

In main, I am iterating through vector of persons and when I find a match, I want to update rect to some new rect or even replace the entire new object 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 {
      ...
    }

The error I am getting at the line I marked by comment is:

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

and also this one:

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

I have tried to erase the object and add a new one but I was still getting the same error. I have read C++ Remove object from vector but I am not sure if this is my problem and I am not using C++11 so these solutions don't work for me.

Is it something with the iterator and my person object when they come to comparison? I think it is but no idea how to solve it.

If you want to compare an object of type person with an object of type Rect (which is what your call to replace implies), then you must provide an appropriate comparison operator to do so in your Person class, like this:

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

Similarly, you need an assignment operator with a signature (and probable implementation) like this:

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

Simplified live demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM