remove_if rearranges a range according to a predicate; it does not erase elements. It moves unwanted values toward the end and returns an iterator marking the new logical end. section 2.3.4
Filtering a vector
Given {0, 1, 2, 3, 4, 5}, a predicate returning true for values less than 3 makes the first three logical elements 3, 4, and 5. Iterate only from begin to new_end; iterating to end also visits leftover elements beyond the logical range. section 2.3.4
Keep these points in mind:
- Store the returned iterator whenever later work must exclude the unwanted elements. section 2.3.4
- Prefer a ranges view when several filtering or transformation steps would make iterator tracking cumbersome. section 2.3.4
Listing 2.13 Using remove_if
auto v = std::vector{ 0, 1, 2, 3, 4, 5 };
auto new_end = std::remove_if(v.begin(), v.end(),
[](int i) { return i < 3; }); #1
std::cout << '\n';
for (int n : v) { #2
std::cout << n << ' ';
}
for (auto it = v.begin(); it != new_end; ++it) { #3
std::cout << *it << ' '; #4
}
A complete vector example shows the predicate, returned new_end iterator, and the difference between traversing the container and traversing its logical result. section 2.3.4
