1. Problem It Solves
C++20 adds concise library operations for prefix/suffix checks, associative membership, predicate erasure, and creating std::array from a built-in array literal. It makes an important assumption visible and checkable.
2. Prerequisites
Strings, associative containers, arrays, and predicates.
You should be able to compile a short program and read its output.
3. Core Idea
These are named intentions: ask text about its edges, ask a set about membership, erase matching elements, and preserve array size in the type. Read std::erase_if as a precise promise; runtime preconditions still belong to the programmer.
4. Minimal Syntax
bool prefix = text.starts_with("log:");
std::erase_if(values, predicate);5. How It Works
The program introduces the smallest relevant form of
std::erase_if.It applies the feature to fixed data while required owners remain in scope.
It prints one result that can be checked against the source.
6. Common Mistakes
containsis C++20 for associative containers, notstd::string::contains; stringcontainsarrives later, so version boundaries matter.Also check the required header, C++20 library support, lifetime, and deduced types.
7. When to Use It
Use it when the named operation exactly matches the intent and improves readability.
Avoid it when you target an older standard library or need a different matching/erasure policy.
8. Simple Example
The program checks a string, queries a set, removes even vector elements, and creates a fixed array. The companion .cpp uses no input, so its result is easy to reproduce.
Complete sample code
Source file
cpp20/33_string_helpers_erase_if_to_array/main.cpp
// Day 33: starts_with, ends_with, contains, erase_if, and to_array
#include <algorithm>
#include <array>
#include <iostream>
#include <set>
#include <string>
#include <vector>
int main() {
std::string text = "log:ready.txt";
std::set<int> ids{2, 4, 8};
std::vector values{1, 2, 3, 4};
int raw[]{7, 8, 9};
auto fixed = std::to_array(raw);
std::erase_if(values, [](int x) { return x % 2 == 0; });
std::cout << std::boolalpha;
std::cout << text.starts_with("log:") << ' ' << text.ends_with(".txt") << '\n';
std::cout << "contains 4 = " << ids.contains(4) << '\n';
std::cout << "remaining = " << values[0] << ',' << values[1] << '\n';
std::cout << "array size = " << fixed.size() << '\n';
}
9. Key Takeaways
std::erase_ifexpresses the central C++20 idea of this day.The example isolates one behavior with fixed data.
Compiler checks do not replace lifetime and runtime reasoning.
Prefer the smallest interface that states the real requirement.
10. Self-Check Questions
Easy — What is the main job of
std::erase_ifin the minimal example?Medium — After
std::erase_ifremoves even values, which values remain and in what order?Hard — Why would replacing
set.contains(key)withtext.contains(fragment)violate this course’s C++20 boundary?