Removing an element from a Vector while preserving order - need a better approach

c++, loops, vector

Solution

You might want to take a look at std::remove_if

bool is_higher_than_10(int i) { return i > 10; }
std::remove_if(v.begin(), v.end(), is_higher_than_10);

And since there's always more to learn, take a look at chris' and Benjamin Lindley's comments and the Erase-remove idiom (thanks guys)

v.erase(std::remove_if(v.begin(), v.end(), is_higher_than_10), v.end());

Problem

I am trying to remove an element from a Vector in C++. In the code below, I am removing an element that is greater than 10 from a list of numbers in Vector. I am using a nested loop to do the deletion. Is there a better or simpler method to do the same. ``` // removing an element from vector preserving order #include <iostream> #include <vector> using namespace std; int main() { vector<int> v {3,2,9,82,2,5,4,3,4,6}; for (int i=0; i < v.size(); i++) { if (v[i] > 10) { // remove element > 10 while (i < v.size()) { v[i] = v[i+1]; i ++; } } } v.pop_back(); for (int i=0; i < v.size(); i++) { cout << v[i] << "|"; } return 0; } ```

Original source