CKTIS / C++
std::erase_if: removing elements that satisfy a predicate
std::erase_if tests elements of a supported container, erases those for which the predicate is true, and returns the removal count.
Version: C++23
Syntax
template<class Key, class T, class Compare, class Allocator, class Predicate>
typename std::map<Key, T, Compare, Allocator>::size_type
erase_if(std::map<Key, T, Compare, Allocator>& c, Predicate pred);
// Corresponding overloads exist for other supported containers.std::erase_if(c, pred) is a family of overloads in container headers. It covers sequence containers and strings as well as ordered, unordered, and C++23 flat associative containers. It does not cover std::array, whose size cannot change.
For vector, deque, and strings, the effect is equivalent to remove_if plus member erase. Ordinary ordered and unordered maps and sets evaluate pred(*it); C++23 flat_map and flat_multimap instead pass pair<const Key&, const T&> to the predicate. The result is size_type, not an iterator.
The predicate should be stable for the examined element and must not invalidate traversal by independently modifying the same container. Exception guarantees, iterator invalidation, and complexity are overload-specific; a predicate exception can leave the container partially modified.
Examples
#include <iostream>
#include <map>
int main() {
std::map<int, int> values{{1, 10}, {2, 20}, {3, 30}};
const auto removed = std::erase_if(values, [](const auto& item) {
return item.first % 2 != 0;
});
std::cout << removed << ' ' << values.size() << ' ' << values.begin()->first << '\n';
}
Result
2 1 2
std::erase_if → 2 1 2