Standard Library Removal Algorithms Removal Algorithms Remove
New to C++'s standard library algorithms? ⇒ Short Introduction
remove
and remove_if
only move the remaining elements
to the front of the input range and don't resize containers or deallocate memory.
If you want to also modify the containing object, e.g., resize/shrink it, then
#include <vector>
#include <iostream>
#include <algorithm>
int main () {
std::vector<int> v {1,2,3,5,2,2,7};
auto re = remove(begin(v), end(v), 2);
// one could re-use the remaining space...
fill(re, end(v), 0);
for (int x : v) { std::cout << x << ' '; } // 1 3 5 7 0 0 0
std::cout << '\n';
// ... or shrink the vector
v.erase(re, end(v));
for (int x : v) { std::cout << x << ' '; } // 1 3 5 7
std::cout << '\n';
}
The output target must be able to receive as many elements as there are in the input range.
#include <vector>
#include <iostream>
#include <algorithm>
int main () {
std::vector<int> in {1,0,1,2,3,5,2,2,7,8};
std::vector<int> out;
out.resize(7);
auto re = remove_copy(begin(in)+2, begin(in)+9, begin(out), 2);
// fit output vector
out.erase(re, end(out));
for (int x : out) { std::cout << x << ' '; } // 1 3 5 7
std::cout << '\n';
}
unique
only moves the remaining elements to the front of the
input range and does not resize containers or deallocate memory.
If you want to also modify the containing object, you have to do
it manually afterwards.
#include <vector>
#include <iostream>
#include <algorithm>
int main () {
std::vector<int> v {4,4,1,5,3,3,3,6,3,3,1};
auto re = unique(begin(v), end(v));
// one could re-use the remaining space...
fill(re, end(v), 0);
for (int x : v) { std::cout << x << ' '; } // 4 1 5 3 6 3 1 0 0 0 0
std::cout << '\n';
// ... or shrink the vector
v.erase(re, end(v));
for (int x : v) { std::cout << x << ' '; } // 4 1 5 3 6 3 1
std::cout << '\n';
}
erase
/ erase_if
erase
/_if
erase
C++20
#include <vector>
#include <deque>
#include <list>
#include <iostream>
#include <algorithm>
int main () {
std::vector<int> v {1,2,3,5,2,2,7};
erase(v, 2);
for (int x : v) { std::cout << x << ' '; } // 1 3 5 7
std::cout << '\n';
std::deque<int> d {1,2,3,5,2,2,7};
erase(d, 2);
for (int x : d) { std::cout << x << ' '; } // 1 3 5 7
std::cout << '\n';
std::list<int> l {1,2,3,5,2,2,7};
erase(l, 2);
for (int x : l) { std::cout << x << ' '; } // 1 3 5 7
std::cout << '\n';
}
Comments…