Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I delete last element of vector

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 ?

like image 635
igor Avatar asked Mar 07 '11 21:03

igor


People also ask

How do you remove the last element of a vector?

pop_back() function is used to pop or remove elements from a vector from the back. The value is removed from the vector from the end, and the container size is decreased by 1.

Can we delete element from vector?

All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.

How do I remove an element from a vector value?

Using the remove() function to remove element by value in vector in C++. We can utilize the remove() function that removes all elements that match a certain specified value. Afterward, the iterator's position is at the new end of the range of elements of the vector.


1 Answers

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;
}
like image 178
Erik Avatar answered Oct 14 '22 22:10

Erik