c++ vector erase current element code example

Example 1: remove value from vector c++

#include <algorithm>
#include <vector>

// using the erase-remove idiom

std::vector<int> vec {2, 4, 6, 8};
int value = 8 // value to be removed
vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end());

Example 2: vector erase specific element

vector.erase( vector.begin() + 3 ); // Deleting the fourth element

Example 3: c++ vector remove element by value

carVec.erase(std::remove_if(carVec.begin(), carVec.end(), [&id_to_delete](const Car& ele)->bool
            {
                return ele.getnewId() == id_to_delete;
            }), carVec.end());

Example 4: 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