1// Deletes the second element (vec[1])
2vec.erase(vec.begin() + 1);
3
4// Deletes the second through third elements (vec[1], vec[2])
5vec.erase(vec.begin() + 1, vec.begin() + 3);
1#include <algorithm>
2#include <vector>
3
4// using the erase-remove idiom
5
6std::vector<int> vec {2, 4, 6, 8};
7int value = 8 // value to be removed
8vec.erase(std::remove(vec.begin(), vec.end(), value), vec.end());
1vector.erase(position) // remove certain position
2// or
3vector.erase(left,right) // remove positions within range
4
1
2
3// erase element from vector by its index
4 vector<string> strs {"first", "second", "third", "last"};
5
6 string element = "third"; // the element which will be erased
7 for(int i=0;i<strs.size();i++)
8 {
9 if(strs[i] == element)
10 strs.erase(strs.begin()+i);
11 }
12
13
1#include <iostream>
2#include <utility>
3#include <vector>
4
5using namespace std;
6
7
8int main()
9{
10 vector< pair<int, int> > v;
11 int N = 5;
12 const int threshold = 2;
13 for(int i = 0; i < N; ++i)
14 v.push_back(make_pair(i, i));
15
16 int i = 0;
17 while(i < v.size())
18 if (v[i].second > threshold)
19 v.erase(v.begin() + i);
20 else
21 i++;
22
23 for(int i = 0; i < v.size(); ++i)
24 cout << "(" << v[i].first << ", " << v[i].second << ")\n";
25
26 cout << "Done" << endl;
27}
1#include<bits/stdc++.h>
2using namespace std;
3int main(){
4 vector<int> v;
5 //Insert values 1 to 10
6 v.push_back(20);
7 v.push_back(10);
8 v.push_back(30);
9 v.push_back(20);
10 v.push_back(40);
11 v.push_back(20);
12 v.push_back(10);
13
14 vector<int>::iterator new_end;
15 new_end = remove(v.begin(), v.end(), 20);
16
17 for(int i=0;i<v.size(); i++){
18 cout << v[i] << " ";
19 }
20 //Prints [10 30 40 10]
21 return 0;
22}
23C++Copy