Removing Elements from a Vector: Two Approaches
Question 1 / 17 • Correct so far: 0 (0 answered)
Manual Erase
void removeEvens(std::vector<int>& v) {
for (auto it = v.begin(); it != v.end(); ) {
if (*it % 2 == 0)
it = v.erase(it);
else
++it;
}
}
auto v = DATA;
removeEvens(v); Erase Remove
void removeEvens(std::vector<int>& v) {
v.erase(
std::remove_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }),
v.end()
);
}
auto v = DATA;
removeEvens(v); Shared test data (shared-setup)
// 10 000 integers [0, 9999]; even values (every other element) are removed.
static const std::vector<int> DATA = []() {
std::vector<int> v(10'000);
std::iota(v.begin(), v.end(), 0);
return v;
}(); Which snippet is faster?
Snippet B is faster. std::remove_if does a single O(n) forward pass, overwriting unwanted elements in-place, then erase trims the tail in one call. Snippet A calls erase inside the loop: each erase shifts all remaining elements one position left, so removing k elements costs O(n * k) total moves — O(n²) when roughly half the elements match.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Erase Remove | 2.4 us | 286.6× |
| Manual Erase | 687 us | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.