liveBook · Manning

Remove_if

As explained in Learn C++ by Example

remove_if is a C++ standard algorithm that rearranges elements according to a predicate and returns an iterator marking the resulting logical end.

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

How Learn C++ by Example covers it

How deep it goes
Explains rearrangement, returned-end tracking, output differences, and ranges as an alternative, but not physical erasure internals.
Examples
Uses a vector of integers, a less-than-three predicate, two loop bounds, and a drop_while view comparison.
What it assumes
Assumes familiarity with vectors, iterators, predicates, loops, and standard algorithms.
What you can do after
Apply it via the C++ standard algorithm and iterate through the returned logical end without reading leftover elements.
How it connects
Connects predicates, iterators, containers, standard algorithms, ranges, and views.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.