1//wiki - erase-remove idiom
2// Use g++ -std=c++11 or clang++ -std=c++11 to compile.
3
4#include <algorithm> // remove and remove_if
5#include <iostream>
6#include <vector> // the general-purpose vector container
7
8void Print(const std::vector<int>& vec) {
9 for (const auto& i : vec) {
10 std::cout << i << ' ';
11 }
12 std::cout << '\n';
13}
14
15int main() {
16 // Initializes a vector that holds numbers from 0-9.
17 std::vector<int> v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
18 Print(v);
19
20 // Removes all elements with the value 5.
21 v.erase(std::remove(v.begin(), v.end(), 5), v.end());
22 Print(v);
23}
24
25/*
26Output:
270 1 2 3 4 5 6 7 8 9
280 1 2 3 4 6 7 8 9
29
30*/
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());
1std::vector<int> v;
2// fill it up somehow
3v.erase(std::remove(v.begin(), v.end(), 99), v.end());
4// really remove all elements with value 99
1vector.erase(position) // remove certain position
2// or
3vector.erase(left,right) // remove positions within range
4
1carVec.erase(std::remove_if(carVec.begin(), carVec.end(), [&id_to_delete](const Car& ele)->bool
2 {
3 return ele.getnewId() == id_to_delete;
4 }), carVec.end());
5
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