c++ for iteration remove code example

Example 1: remove element from vector on condition c++

v.erase(std::remove_if(
    v.begin(), v.end(),
    [](const int& x) { 
        return x > 10; // put your condition here
    }), v.end());
// therefore elements > 10 are removed, leaving only elements<= 10

Example 2: removing element from vector while iterating c++

#include <iostream>
#include <vector>
#include <algorithm>
 
int main()
{
    std::vector<int> v = { 1, 2, 3, 4, 5, 6 };
 
    auto it = v.begin();
    while (it != v.end())
    {
        // specify condition for removing element; in this case remove odd numbers
        if (*it & 1) {
            // erase() invalidates the iterator, use returned iterator
            it = v.erase(it);
        }
        // Notice that iterator is incremented only on the else part (why?)
        else {
            ++it;
        }
    }
 
    for (int const &i: v) {
        std::cout << i << ' ';
    }
 
    return 0;
}

Tags:

Cpp Example