C++
vector
filtering
algorithm
programming tips

Efficient way to filter out elements from stdvector

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

The efficient way to remove elements from a std::vector is usually the erase-remove idiom, or std::erase_if if you are using C++20. This works well because it keeps the vector contiguous, moves the elements you want to keep to the front, and then trims the unwanted tail in one logical pattern.

Why Simple Erase-in-a-Loop Is Usually Wrong

Beginners often write something like:

cpp
1for (auto it = values.begin(); it != values.end(); ++it) {
2    if (should_remove(*it)) {
3        values.erase(it);
4    }
5}

That is problematic because:

  • 'erase invalidates iterators at and after the erased position,'
  • it can lead to skipped elements if the loop is written incorrectly,
  • and repeated erasures from the middle cause repeated element shifting.

It can be made correct with careful iterator handling, but it is rarely the best pattern.

The Erase-Remove Idiom

The classic solution is:

cpp
1#include <algorithm>
2#include <vector>
3#include <iostream>
4
5int main() {
6    std::vector<int> values = {1, 2, 3, 4, 5, 6};
7
8    values.erase(
9        std::remove_if(values.begin(), values.end(),
10                       [](int x) { return x % 2 == 0; }),
11        values.end()
12    );
13
14    for (int x : values) {
15        std::cout << x << ' ';
16    }
17}

This keeps only the odd numbers.

What happens internally:

  1. std::remove_if partitions the range so kept elements are moved to the front,
  2. it returns an iterator to the new logical end,
  3. erase removes the leftover tail from the vector.

This is linear time and preserves the order of the kept elements.

C++20: Use std::erase_if

If you are on C++20 or later, the standard library gives you a cleaner wrapper:

cpp
1#include <vector>
2#include <iostream>
3
4int main() {
5    std::vector<int> values = {1, 2, 3, 4, 5, 6};
6
7    std::erase_if(values, [](int x) { return x % 2 == 0; });
8
9    for (int x : values) {
10        std::cout << x << ' ';
11    }
12}

This is usually the nicest answer today because it expresses intent directly and avoids repeating the idiom manually.

If You Need to Keep the Original Vector

Sometimes you do not want in-place filtering at all. In that case, create a new vector with std::copy_if:

cpp
1#include <algorithm>
2#include <vector>
3#include <iterator>
4#include <iostream>
5
6int main() {
7    std::vector<int> values = {1, 2, 3, 4, 5, 6};
8    std::vector<int> filtered;
9
10    std::copy_if(values.begin(), values.end(),
11                 std::back_inserter(filtered),
12                 [](int x) { return x % 2 == 1; });
13
14    for (int x : filtered) {
15        std::cout << x << ' ';
16    }
17}

This is often clearer when:

  • the original vector must remain unchanged,
  • or the filtered result is logically a new collection.

It uses extra memory, but sometimes that is exactly the right tradeoff.

Order Preservation and Complexity

One nice property of the erase-remove approach is that it preserves the relative order of kept elements. That matters in many real programs.

Complexity is linear in the vector size. There will still be element moves, because a vector is contiguous storage, but you avoid repeated middle erasures that repeatedly shift the tail.

So the real advantage is not "zero movement." It is "one linear compaction pass instead of many expensive partial shifts."

When a Different Container Might Be Better

If your workload constantly removes elements from arbitrary positions and insertion/erase behavior dominates, a std::vector may not be the ideal container.

Still, do not switch containers too quickly. Vectors are extremely cache-friendly, and even with occasional filtering they often outperform pointer-heavy alternatives.

Choose a different container only when the operation pattern truly demands it.

Filtering by Partitioning

If you do not care about preserving order, std::partition can also be useful:

cpp
auto middle = std::partition(values.begin(), values.end(),
                             [](int x) { return x % 2 == 1; });
values.erase(middle, values.end());

This can be a valid optimization in some cases, but most of the time order-preserving filtering is what people actually want.

Common Pitfalls

The biggest pitfall is erasing from the vector inside a simple loop without handling iterator invalidation correctly.

Another mistake is assuming std::remove_if actually shrinks the container by itself. It does not; you still need erase, unless you use std::erase_if.

Developers also sometimes switch away from std::vector too quickly. For many workloads, a vector plus erase-remove is still the best-performing and simplest solution.

Finally, be explicit about whether order matters. If it does, prefer remove/erase or erase_if. If it does not, partition-based approaches may be acceptable.

Summary

  • The standard in-place solution is the erase-remove idiom.
  • In C++20, std::erase_if is the cleanest way to express the same idea.
  • Use std::copy_if when you want a filtered copy and need to keep the original vector.
  • Filtering a vector is still linear time, but done correctly it avoids repeated expensive erasures.
  • Be careful about iterator invalidation when erasing inside loops.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms