std::ranges...copy_result,(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’… std::ranges::remove_copy, std::ranges::remove_copy_if, std::ranges::remove_copy_result

okay so quick vibe check first: this page lives in the C++ Standard Library (libstdc++ / C++ standard library man pages, the <algorithm> girlies) and it's a long one, so bestie, this is part 1 of 2 πŸ’–

We're talking about the remove_copy family β€” the "copy everything EXCEPT the stuff I don't want" algorithms. Absolutely iconic behaviour, no notes.


πŸŽ€ NAME πŸŽ€

std::ranges::remove_copy, std::ranges::remove_copy_if, std::ranges::remove_copy_result

(also the remove_copy_if_result situation, which we'll get to, iykyk ✨)


✨ SYNOPSIS ✨

Defined in header <algorithm> β€” literally the header, main character energy 🌸

πŸ¦‹ Call signature β€” the remove_copy overloads

Number (1) is the iterator-pair one. It got a glow-up in C++26, so there are two flavors:

(1) β€” until C++26 (the original C++20 version):

template< std::input_iterator I, std::sentinel_for<I> S,
          std::weakly_incrementable O, class T, class Proj = std::identity >
requires std::indirectly_copyable<I, O> &&
             std::indirect_binary_predicate
                 <ranges::equal_to, std::projected<I, Proj>, const T*>
constexpr remove_copy_result<I, O>
    remove_copy( I first, S last, O result, const T& value,
                 Proj proj = {} );

(1) β€” since C++26 (same vibe, T now defaults):

template< std::input_iterator I, std::sentinel_for<I> S,
          std::weakly_incrementable O, class Proj = std::identity,
          class T = std::projected_value_t<I, Proj> >
requires std::indirectly_copyable<I, O> &&
             std::indirect_binary_predicate
                 <ranges::equal_to, std::projected<I, Proj>, const T*>
constexpr remove_copy_result<I, O>
    remove_copy( I first, S last, O result, const T& value,
                 Proj proj = {} );

Number (2) is the range version β€” same energy, but you hand it a range instead of two iterators:

(2) β€” until C++26:

template< ranges::input_range R,
          std::weakly_incrementable O, class T, class Proj = std::identity >
requires std::indirectly_copyable<ranges::iterator_t<R>, O> &&
             std::indirect_binary_predicate
                 <ranges::equal_to,
                  std::projected<ranges::iterator_t<R>, Proj>, const T*>
constexpr remove_copy_result<ranges::borrowed_iterator_t<R>, O>
    remove_copy( R&& r, O result, const T& value, Proj proj = {} );

(2) β€” since C++26:

template< ranges::input_range R,
          std::weakly_incrementable O, class Proj = std::identity,
          class T = std::projected_value_t<ranges::iterator_t<R>, Proj> >
requires std::indirectly_copyable<ranges::iterator_t<R>, O> &&
             std::indirect_binary_predicate
                 <ranges::equal_to,
                  std::projected<ranges::iterator_t<R>, Proj>, const T*>
constexpr remove_copy_result<ranges::borrowed_iterator_t<R>, O>
    remove_copy( R&& r, O result, const T& value, Proj proj = {} );

🌈 Call signature β€” the remove_copy_if overloads

(3) β€” since C++20, iterator pair + a predicate:

template< std::input_iterator I, std::sentinel_for<I> S,
          std::weakly_incrementable O, class Proj = std::identity,
          std::indirect_unary_predicate<std::projected<I, Proj>> Pred >
requires std::indirectly_copyable<I, O>
constexpr remove_copy_if_result<I, O>
    remove_copy_if( I first, S last, O result, Pred pred, Proj proj = {} );

(4) β€” since C++20, range version with a predicate:

template< ranges::input_range R,
          std::weakly_incrementable O, class Proj = std::identity,
          std::indirect_unary_predicate<
              std::projected<ranges::iterator_t<R>, Proj>> Pred >
requires std::indirectly_copyable<ranges::iterator_t<R>, O>
constexpr remove_copy_if_result<ranges::borrowed_iterator_t<R>, O>
    remove_copy_if( R&& r, O result, Pred pred, Proj proj = {} );

🧚 Helper types

(5) β€” since C++20:

template< class I, class O >
using remove_copy_result = ranges::in_out_result<I, O>;

(6) β€” since C++20:

template< class I, class O >
using remove_copy_if_result = ranges::in_out_result<I, O>;

πŸ’œ DESCRIPTION πŸ’œ

So what it actually does: it copies elements from the source range [first, last) over to the destination range beginning at result, and it omits the elements that β€” after being projected by proj β€” satisfy whatever criteria you set up. It's the "you're not coming to the party" algorithm πŸŽ€

🫢 REAL TALK, bestie: the behavior is undefined if the source and destination ranges overlap. Not "kinda weird", not "might be fine" β€” undefined. So don't be cute with overlapping ranges, fr fr 😭
  • (1) Ignores all elements that are equal to value.
  • (3) Ignores all elements for which predicate pred returns true.
  • (2, 4) Same as (1, 3), but uses r as the source range, as if using ranges::begin(r) as first, and ranges::end(r) as last.

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

  • Explicit template argument lists cannot be specified when calling any of them.
  • None of them are visible to argument-dependent lookup.
  • When any of them are found by normal unqualified lookup as the name to the left of the function-call operator, argument-dependent lookup is inhibited.

In practice, they may be implemented as function objects, or with special compiler extensions. (Sneaky? a little. Iconic? absolutely πŸ’…)


πŸ“ PARAMETERS πŸ“

  • first, last β€” the source range of elements
  • r β€” the source range of elements
  • result β€” the beginning of the destination range
  • value β€” the value of the elements not to copy
  • comp β€” the binary predicate to compare the projected elements
  • proj β€” the projection to apply to the elements

πŸ‘‘ RETURN VALUE πŸ‘‘

{last, result + N}, where N is the number of elements copied. yes, it hands you back a little bundle of both ends, slay ✨


⭐ COMPLEXITY ⭐

Exactly ranges::distance(first, last) applications of the corresponding predicate comp and any projection proj.

Not "about", not "at most" β€” exactly. We respect a precise queen πŸ’…


πŸ¦‹ NOTES πŸ¦‹

The algorithm is stable, i.e. preserves the relative order of the copied elements. So the order you gave it is the order you get back. No chaos, no shuffling, we love to see it πŸ’–

πŸ”¬ Feature-test macro

  • __cpp_lib_algorithm_default_value_type β€” value 202403, (C++26) β€” feature: List-initialization for algorithms (1,2)

🌸 POSSIBLE IMPLEMENTATION 🌸

Here's roughly how the girlies implement it. Cute, right? πŸŽ€

πŸ’« remove_copy

struct remove_copy_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S,
             std::weakly_incrementable O, class Proj = std::identity,
             class T = std::projected_value_t<I, Proj>>
    requires std::indirectly_copyable<I, O> &&
             std::indirect_binary_predicate<ranges::equal_to,
                                            std::projected<I, Proj>,
                                            const T*>
    constexpr ranges::remove_copy_result<I, O>
        operator()(I first, S last, O result, const T& value, Proj proj = {}) const
    {
        for (; !(first == last); ++first)
            if (value != std::invoke(proj, *first))
            {
                *result = *first;
                ++result;
            }
        return {std::move(first), std::move(result)};
    }

    template<ranges::input_range R,
             std::weakly_incrementable O, class Proj = std::identity,
             class T = std::projected_value_t<ranges::iterator_t<R>, Proj>>
    requires std::indirectly_copyable<ranges::iterator_t<R>, O> &&
             std::indirect_binary_predicate<ranges::equal_to,
             std::projected<ranges::iterator_t<R>, Proj>, const T*>
    constexpr
    ranges::remove_copy_result<ranges::borrowed_iterator_t<R>, O>
        operator()(R&& r, O result, const T& value, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::move(result), value,
                       std::move(proj));
    }
};

inline constexpr remove_copy_fn remove_copy {};

πŸ’« remove_copy_if

struct remove_copy_if_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O,
             class Proj = std::identity,
             std::indirect_unary_predicate<std::projected<I, Proj>> Pred>
    requires std::indirectly_copyable<I, O>
    constexpr ranges::remove_copy_if_result<I, O>
        operator()(I first, S last, O result, Pred pred, Proj proj = {}) const
    {
        for (; first != last; ++first)
            if (false == std::invoke(pred, std::invoke(proj, *first)))
            {
                *result = *first;
                ++result;
            }
        return {std::move(first), std::move(result)};
    }

    template<ranges::input_range R, std::weakly_incrementable O,
             class Proj = std::identity,
             std::indirect_unary_predicate<
                 std::projected<ranges::iterator_t<R>, Proj>> Pred>
    requires std::indirectly_copyable<ranges::iterator_t<R>, O>
    constexpr
    ranges::remove_copy_if_result<ranges::borrowed_iterator_t<R>, O>
        operator()(R&& r, O result, Pred pred, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::move(result),
                       std::move(pred), std::move(proj));
    }
};

inline constexpr remove_copy_if_fn remove_copy_if {};

and that's the whole first half, bestie β€” part 2 is coming right up, don't you dare close the tab πŸ˜­πŸ’–

🌸 EXAMPLE 🌸

okay bestie, this example is doing the absolute most in the best way: it filters the hash symbol out of a string, copies only the complex numbers with a positive imaginary part, and shows off default value type deduction. the comments in the code are your little tour guides ✨

// Run this code

#include <algorithm>
#include <array>
#include <complex>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string_view>
#include <vector>

void println(const auto rem, const auto& v)
{
    std::cout << rem << ' ';
    for (const auto& e : v)
        std::cout << e << ' ';
    std::cout << '\n';
}

int main()
{
    // Filter out the hash symbol from the given string.
    const std::string_view str{"#Small #Buffer #Optimization"};
    std::cout << "before: " << std::quoted(str) << '\n';

    std::cout << "after:  \"";
    std::ranges::remove_copy(str.begin(), str.end(),
                             std::ostream_iterator<char>(std::cout),
       '#');
    std::cout << "\"\n";

    // Copy only the complex numbers with positive imaginary part.
    using Ci = std::complex<int>;
    constexpr std::array<Ci, 5> source
    {
        Ci{1, 0}, Ci{0, 1}, Ci{2, -1}, Ci{3, 2}, Ci{4, -3}
    };
    std::vector<std::complex<int>> target;

    std::ranges::remove_copy_if
    (
        source,
        std::back_inserter(target),
        [](int imag) { return imag <= 0; },
        [](Ci z) { return z.imag(); }
    );

    println("source:", source);
    println("target:", target);

    std::vector<std::complex<float>> nums{{2, 2}, {1, 3}, {4, 8}, {1,
       3}};
    std::vector<std::complex<double>> outs;
    #ifdef __cpp_lib_algorithm_default_value_type
        std::remove_copy(nums.cbegin(), nums.cend(),
       std::back_inserter(outs),
                                 {1, 3}); // T gets deduced to
       std::complex<float>
    #else
        std::remove_copy(nums.cbegin(), nums.cend(),
       std::back_inserter(outs),
                                 std::complex<float>{1, 3});
    #endif
    println("nums:  ", nums);
    println("outs:  ", outs);
}

Output:

before: "#Small #Buffer #Optimization"
after:  "Small Buffer Optimization"
source: (1,0) (0,1) (2,-1) (3,2) (4,-3)
target: (0,1) (3,2)
nums:   (2,2) (1,3) (4,8) (1,3)
outs:   (2,2) (4,8)

🌈 SEE ALSO 🌈

the whole algorithm friend group is here, and yes they all ate πŸ’…

  • ranges::remove, ranges::remove_if β€” removes elements satisfying specific criteria (C++20) (niebloid)
  • ranges::copy, ranges::copy_if β€” copies a range of elements to a new location (C++20) (niebloid)
  • ranges::copy_n β€” copies a number of elements to a new location (C++20) (niebloid)
  • ranges::copy_backward β€” copies a range of elements in backwards order (C++20) (niebloid)
  • ranges::replace_copy, ranges::replace_copy_if β€” copies a range, replacing elements satisfying specific criteria with another value (C++20) (niebloid)
  • ranges::reverse_copy β€” creates a copy of a range that is reversed (C++20) (niebloid)
  • ranges::rotate_copy β€” copies and rotate a range of elements (C++20) (niebloid)
  • ranges::unique_copy β€” creates a copy of some range of elements that contains no consecutive duplicates (C++20) (niebloid)
  • remove_copy, remove_copy_if β€” copies a range of elements omitting those that satisfy specific criteria (function template)

πŸ’– source: http://cppreference.com Β· version/date: 2024.06.10 Β· page: std::ranges...copy_result,(3) β€” that’s the whole manual page, bestie. go copy, remove, and slay responsibly. mwah πŸ’‹βœ¨

πŸ“¦ where this page comes from