Why can't I delete last element of vector

和自甴很熟 提交于 2021-02-07 14:24:27

问题


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 ?


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



回答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);
}



回答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.



来源:https://stackoverflow.com/questions/5225229/why-cant-i-delete-last-element-of-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!