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
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// Why not setup a lambda you can use again & again
2auto removeByIndex =
3 []<class T>(std::vector<T> &vec, unsigned int index)
4{
5 // This is the meat & potatoes
6 vec.erase(vec.begin() + index);
7};
8
9// Then you can throw whatever vector at it you desire
10std::vector<std::string> stringvec = {"Hello", "World"};
11// Will remove index 1: "World"
12removeByIndex(stringvec, 1);
13// Vector of integers, we will use push_back
14std::vector<unsigned int> intvec;
15intvec.push_back(33);
16intvec.push_back(66);
17intvec.push_back(99);
18// Will remove index 2: 99
19removeByIndex(intvec, 2);