vector remove specific 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: delete from front in vector c++

// Deleting first element
vector_name.erase(vector_name.begin());

// Deleting xth element from start
vector_name.erase(vector_name.begin()+(x-1));

// Deleting from the last
vector_name.pop_back();

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());

Tags:

Cpp Example