erase vector from loop c++ code example

Example 1: erase an element from vector c++

#include<bits/stdc++.h>
using namespace std;
int main(){
    vector<int> v;
    //Insert values 1 to 10
    v.push_back(20);
    v.push_back(10);
    v.push_back(30);
    v.push_back(20);
    v.push_back(40);
    v.push_back(20);
    v.push_back(10);

    vector<int>::iterator new_end;
    new_end = remove(v.begin(), v.end(), 20);

    for(int i=0;i<v.size(); i++){
        cout << v[i] << " ";
    }
    //Prints [10 30 40 10]
    return 0;
}
C++Copy

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