The Wayback Machine - https://web.archive.org/web/20210413015921/https://en.cppreference.com/w/cpp/algorithm/ranges/remove
Namespaces
Variants
Views
Actions

std::ranges::remove, std::ranges::remove_if

From cppreference.com
< cpp‎ | algorithm‎ | ranges
 
 
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms: std::ranges::copy, std::ranges::sort, ...
Execution policies (C++17)
Non-modifying sequence operations
(C++11)(C++11)(C++11)
(C++17)
Modifying sequence operations
Operations on uninitialized storage
Partitioning operations
Sorting operations
(C++11)
Binary search operations
Set operations (on sorted ranges)
Heap operations
(C++11)
Minimum/maximum operations
(C++11)
(C++17)

Permutations
Numeric operations
C library
 
Constrained algorithms
Non-modifying sequence operations
Modifying sequence operations
Operations on uninitialized storage
Partitioning operations
Sorting operations
Binary search operations
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutations
 
Defined in header <algorithm>
Call signature
template<std::permutable I, std::sentinel_for<I> S, class T, class Proj = std::identity>

  requires std::indirect_binary_predicate<
      ranges::equal_to, std::projected<I, Proj>, const T*>
    constexpr ranges::subrange<I>

      ranges::remove( I first, S last, const T& value, Proj proj = {} );
(1) (since C++20)
template<ranges::forward_range R, class T, class Proj = std::identity>

  requires std::permutable<ranges::iterator_t<R>> &&
             std::indirect_binary_predicate<
               ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*>
    constexpr ranges::borrowed_subrange_t<R>

      ranges::remove( R&& r, const T& value, Proj proj = {} );
(2) (since C++20)
template<std::permutable I, std::sentinel_for<I> S, class Proj = std::identity,

         std::indirect_unary_predicate<std::projected<I, Proj>> Pred>
  constexpr ranges::subrange<I>

    ranges::remove_if( I first, S last, Pred pred, Proj proj = {} );
(3) (since C++20)
template<ranges::forward_range R, class Proj = std::identity,

         std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred>
  requires std::permutable<ranges::iterator_t<R>>
    constexpr ranges::borrowed_subrange_t<R>

      ranges::remove_if( R&& r, Pred pred, Proj proj = {} );
(4) (since C++20)
1) Removes all elements that are equal to value, using std::invoke(proj, *i) == value to compare.
3) Removes all elements for which std::invoke(pred, invoke(proj, *i)) returns true.
2,4) Same as (1,3), but uses r as the range, as if using ranges::begin(r) as first and ranges::end(r) as last.

Effect: removes all elements satisfying specific criteria from the range [first, last) and returns a subrange [ret, last), where ret is a past-the-end iterator for the new end of the range.

Removing is done by shifting (by means of move assignment) the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range. Relative order of the elements that remain is preserved and the physical size of the container is unchanged. Iterators pointing to an element between the new logical end and the physical end of the range are still dereferenceable, but the elements themselves have unspecified values (as per MoveAssignable post-condition).

A call to ranges::remove is typically followed by a call to a container's erase member function, which erases the unspecified values and reduces the physical size of the container to match its new logical size. These two invocations together constitute a so-called Erase–remove idiom. Since C++20, the same effect can be achieved using only one call to the free function std::erase that has overloads for all sequential standard containers, or using std::erase_if that has overloads for all standard containers.

The function-like entities described on this page are niebloids, that is:

In practice, they may be implemented as function objects, or with special compiler extensions.

Contents

[edit] Parameters

first, last - the range of elements to process
r - the range of elements to process
value - the value of elements to remove
pred - predicate to apply to the projected elements
proj - projection to apply to the elements

[edit] Return value

An object {ret, last}, where ret is a past-the-end iterator for a new subrange of the values all in valid but unspecified state.

[edit] Complexity

Exactly N applications of the corresponding predicate and any projection, where N = (last - first), and N-1 move operations at worst.

[edit] Notes

The similarly-named container member functions list::remove, list::remove_if, forward_list::remove, and forward_list::remove_if erase the removed elements.

These algorithms cannot be used with associative containers such as std::set and std::map because ForwardIt does not dereference to a MoveAssignable type (the keys in these containers are not modifiable).

Because ranges::remove takes value by reference, it can have unexpected behavior if it is a reference to an element of the range [first, last).

[edit] Possible implementation

First version
struct remove_fn {
  template<std::permutable I, std::sentinel_for<I> S, class T, class Proj = std::identity>
    requires std::indirect_binary_predicate<
        ranges::equal_to, std::projected<I, Proj>, const T*>
      constexpr ranges::subrange<I>
        operator()( I first, S last, const T& value, Proj proj = {} ) const {
            first = ranges::find(std::move(first), last, value, proj);
            if (first != last) {
                for (I i { std::next(first) }; i != last; ++i) {
                    if (value != std::invoke(proj, *i)) {
                        *first = ranges::iter_move(i);
                        ++first;
                    }
                }
            }
            return {first, last};
        }
 
  template<ranges::forward_range R, class T, class Proj = std::identity>
    requires std::permutable<ranges::iterator_t<R>> &&
               std::indirect_binary_predicate<
                 ranges::equal_to, std::projected<ranges::iterator_t<R>, Proj>, const T*>
      constexpr ranges::borrowed_subrange_t<R>
        operator()( R&& r, const T& value, Proj proj = {} ) const {
          return (*this)(ranges::begin(r), ranges::end(r), value, std::move(proj));
        }
};
 
inline constexpr remove_fn remove{};
Second version
struct remove_if_fn {
  template<std::permutable I, std::sentinel_for<I> S, class Proj = std::identity,
           std::indirect_unary_predicate<std::projected<I, Proj>> Pred>
    constexpr ranges::subrange<I>
      operator()( I first, S last, Pred pred, Proj proj = {} ) const {
          first = ranges::find_if(std::move(first), last, pred, proj);
          if (first != last) {
              for (I i { std::next(first) }; i != last; ++i) {
                  if (!std::invoke(pred, std::invoke(proj, *i))) {
                      *first = ranges::iter_move(i);
                      ++first;
                  }
              }
          }
          return {first, last};
      }
 
  template<ranges::forward_range R, class Proj = std::identity,
           std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>, Proj>> Pred>
    requires std::permutable<ranges::iterator_t<R>>
      constexpr ranges::borrowed_subrange_t<R>
        operator()( R&& r, Pred pred, Proj proj = {} ) const {
          return (*this)(ranges::begin(r), ranges::end(r), pred, std::move(proj));
        }
  };
 
inline constexpr remove_if_fn remove_if{};

[edit] Example

#include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
 
int main()
{
    std::string ndr{"N o _ D i a g n o s t i c _ R e q u i r e d"};
    std::cout << std::quoted(ndr) << " -> ";
    const auto ret1 = std::ranges::remove(ndr, ' ');
    ndr.erase(ret1.begin(), ret1.end());
    std::cout << std::quoted(ndr) << "\n\n";
 
    auto rm = [](char c) { return std::islower(c) or std::isspace(c); };
    std::string sfinae{"Substitution Failure Is Not An Error"};
    std::cout << std::quoted(sfinae) << " -> ";
    const auto ret2 = std::ranges::remove_if(sfinae, rm);
    sfinae.erase(ret2.begin(), ret2.end());
    std::cout << std::quoted(sfinae) << '\n';
}

Output:

"N o _ D i a g n o s t i c _ R e q u i r e d" -> "No_Diagnostic_Required"
 
"Substitution Failure Is Not An Error" -> "SFINAE"

[edit] See also

copies a range of elements omitting those that satisfy specific criteria
(niebloid) [edit]
removes consecutive duplicate elements in a range
(niebloid) [edit]
removes elements satisfying specific criteria
(function template) [edit]