Removing a Vector Element: Stable vs Swap Removal
Question 48 / 51 • Correct so far: 0 (0 answered)
Erase Middle
void removeMany(std::vector<int>& v, std::size_t count) {
for (std::size_t i = 0; i < count; ++i) {
std::size_t pos = v.size() / 2;
v.erase(v.begin() + static_cast<std::ptrdiff_t>(pos));
}
}
removeMany(v, kRemovalsPerRun); Swap Pop
void removeMany(std::vector<int>& v, std::size_t count) {
for (std::size_t i = 0; i < count; ++i) {
std::size_t pos = v.size() / 2;
std::swap(v[pos], v.back());
v.pop_back();
}
}
removeMany(v, kRemovalsPerRun); Shared test data (shared-setup)
constexpr std::size_t kVecSize = 8192;
constexpr std::size_t kRemovalsPerRun = 1024;
static std::vector<int> makeData() {
std::vector<int> v(kVecSize);
std::iota(v.begin(), v.end(), 0);
return v;
}
static const std::vector<int> ORIGINAL = makeData(); Which snippet is faster?
Snippet B is faster when order does not matter. Erasing from the middle of a vector shifts many elements, while swap-and-pop does constant work: swap one element with the back, then pop.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Erase Middle | 99.8 us | 1.0× |
| Swap Pop | 828 ns | 120.5× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.