M
M
Mr. Vazovsky2018-02-21 09:58:31
C++ / C#
Mr. Vazovsky, 2018-02-21 09:58:31

How to remove an element of a vector inside a loop?

Hello gentlemen comrades! There is a vector of pointers to class objects. Loop through all the elements of the given vector. It is necessary, when a certain condition is met, to remove an element inside the loop. How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2018-02-21
@D3Nd3R

You can do everything without a loop:

contours.erase(std::remove_if(contours.begin(), contours.end(),
    [this](std::vector<cv::Point> vec)->bool
                         {return vec.size() < this->mParams.minContourSize; })
    ,contours.end());

M
Maxim Grishin, 2018-02-21
@vesper-bot

Iterate from the end, after which, to delete, you can move the tail element to the place of the one being deleted and reduce the length of the vector by 1 (in metadata, that is, if you have a class with a vector, you reduce the field indicating the number of significant elements in the vector). Otherwise, only by copying the region, because C does not know how to make arrays of variable length, the programmer needs to take care of this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question