15 Different Ways to Filter Containers in Modern C++ -- Bartłomiej Filipek

logo.pngFiltering items from a container is a common situation. Bartłomiej Filipek demonstrates various approaches from different versions of C++.

15 Different Ways to Filter Containers in Modern C++

by Bartłomiej Filipek

From the article:

Do you know how many ways we can implement a filter function in C++? While the problem is relatively easy to understand – take a container, copy elements that match a predicate and the return a new container – it’s good to exercise with the C++ Standard Library and check a few ideas. We can also apply some modern C++ techniques, including C++23. Let’s start!

The problem statement

To be precise by a filter, I mean a function with the following interface:

  auto Filter(const Container& cont,
              UnaryPredicate p) {}

It takes a container and a predicate, and then it creates an output container with elements that satisfy the predicate. We can use it like the following:

  const std::vector<std::string> vec{
    "Hello", "**txt", "World", "error", "warning",
    "C++", "****" };
  auto filtered = Filter(vec, [](auto& elem) {
    return !elem.starts_with('*'); });
    // filtered should have "Hello", "World",
    // "error", "warning", "C++"

Writing such a function can be a good exercise with various options and algorithms in the Standard Library. What’s more, our function hides internal things like iterators, so it’s more like a range-based version.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.