1

I have simple question. I have a vector:

vector<int> SomeVector;

which has some elements inside, say:

{-1, -1, -1, -1, 3, 8, 255}

Is there a way to remove all elements with value -1 from this vector using pop_back? Or if there is any other way that would also be welcomed BUT:

  • I may not know the index of the elements with value -1
  • I may not know how many -1's there are in the vector

Just a new student here, any help would be great, thanks in advance...

byetisener
  • 310
  • 2
  • 11

1 Answers1

1

I would use the erase-remove idiom for such a task

// Remove all elements with value -1 from the vector
vec.erase(std::remove(vec.begin(), vec.end(), -1), vec.end());

Using just pop_back in combination with something like back() would treat the vector as a stack and pop off as many -1 as there are at its end.

Marco A.
  • 43,032
  • 26
  • 132
  • 246