Why I can not delete the last element of the vector

I have a stl vector consisting of several elements. I need to iterate over this vector and remove elements that meet some criteria. So I wrote this code

for (int j = imageDataVector.size()-1; j >= 0; j--) {
    if(imageDataVector[i] < threshold)
        imageDataVector.erase(imageDataVector.end() - j);
}

This code is perfect for almost all cases, however, if all the elements of the vector meet the criteria, I get an error message:

vector erase iterator outside the range

This error occurs if only one element remains in the vector. What am I doing wrong?

+5
source share
3 answers
if(imageDataVector[i] < threshold)
        imageDataVector.erase(imageDataVector.end()-j);

Must be:

if(imageDataVector[j] < threshold)
        imageDataVector.erase(imageDataVector.begin()+j);

EDIT: for completeness, how to remove and remove the iterator:

imageDataVector.erase(std::remove_if(imageDataVector.begin(), imageDataVector.end(), std::bind2nd(std::less<vector_data_type>(), threshold)), imageDataVector.end());

vector<type>::iterator it = imageDataVector.begin();
while (it != imageDataVector.end()) {
  if (*it < threshold)
    it = imageDataVector.erase(it);
  else
    ++it;
}
+11
source

You mix indexing back and forth.

std::remove_if. , , .

:

imageDataVector.erase(std::remove_if(imageDataVector.begin(), imageDataVector.end(), std::bind2nd(std::less<data_type>(), threshold)), imageDataVector.end());

, , , .

for (int j=imageDataVector.size()-1 ;j>=0;j--)
{
    if(imageDataVector[i] < threshold)
        imageDataVector.erase(imageDataVector.begin()+j);
}
+6

You are trying to count j to zero, and is imageDataVector.end() - 0not a valid iterator. In standard C ++ library containers, the final iterator points one after the last element, not the last element.

+3
source

All Articles