c++ vector remove element code example
Example 1: remove element by index from vector c++
vec.erase(vec.begin() + 1);
vec.erase(vec.begin() + 1, vec.begin() + 3);
Example 2: remove value from vector c++
#include <algorithm>
#include <vector>
std::vector<int> vec {2, 4, 6, 8};
int value = 8
vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end());
Example 3: delete from front in vector c++
vector_name.erase(vector_name.begin());
vector_name.erase(vector_name.begin()+(x-1));
vector_name.pop_back();
Example 4: how to remove an element from a vector by value c++
std::vector<int> v;
v.erase(std::remove(v.begin(), v.end(), 99), v.end());
Example 5: c++ remove element from vector
vector.erase(position)
vector.erase(left,right)
Example 6: erase an element from vector c++
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int> v;
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] << " ";
}
return 0;
}
C++Copy