Why can't I delete last element of vector

12,430

Solution 1

if(imageDataVector[i] < threshold)
        imageDataVector.erase(imageDataVector.end()-j);

Should likely be:

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

EDIT: for completeness, the erase-remove way and the iterator way:

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

Solution 2

You're mixing forward and backward indexing.

I'd consider using std::remove_if instead. That way if you're removing multiple elements you don't shift the entire vector forwards on each erase.

It would look something like this:

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

Alternately try the following, noting that it will result in a lot of movement if you remove multiple items from the vector.

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

Solution 3

You're trying to count down j to zero, and imageDataVector.end() - 0 is not a valid iterator. In the standard C++ library containers, the end iterator points one past the last element, not at the last element.

Share:
12,430
igor
Author by

igor

Updated on June 04, 2022

Comments

  • igor
    igor almost 2 years

    I have stl vector consisting of several elements. I need to iterate through this vector and delete elements which meets 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 works fine for almost all cases, however if all elements of vector meets the criteria I get an error:

    vector erase iterator outside the range
    

    This error occurs if I have only one element left in the vector. What do I do wrong ?