Namespaces
Variants

std::ranges:: copy, std::ranges:: copy_if, std::ranges:: copy_result, std::ranges:: copy_if_result

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
헤더 파일에 정의됨 <algorithm>
호출 시그니처
template < std:: input_iterator I, std:: sentinel_for < I > S, std:: weakly_incrementable O >

requires std:: indirectly_copyable < I, O >
constexpr copy_result < I, O >

copy ( I first, S last, O result ) ;
(1) (C++20 이후)
template < ranges:: input_range R, std:: weakly_incrementable O >

requires std:: indirectly_copyable < ranges:: iterator_t < R > , O >
constexpr copy_result < ranges:: borrowed_iterator_t < R > , O >

copy ( R && r, O result ) ;
(2) (C++20 이후)
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 copy_if_result < I, O >

copy_if ( I first, S last, O result, Pred pred, Proj proj = { } ) ;
(3) (C++20 이후)
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 copy_if_result < ranges:: borrowed_iterator_t < R > , O >

copy_if ( R && r, O result, Pred pred, Proj proj = { } ) ;
(4) (C++20 이후)
헬퍼 타입
template < class I, class O >
using copy_result = ranges:: in_out_result < I, O > ;
(5) (C++20 이후)
template < class I, class O >
using copy_if_result = ranges:: in_out_result < I, O > ;
(6) (C++20 이후)

[ first , last ) 범위에 정의된 요소들을 result 에서 시작하는 다른 범위로 복사합니다.

1) 범위 [ first , last ) 내의 모든 요소를 first 부터 시작하여 last - 1 까지 진행하며 복사합니다. result 가 범위 [ first , last ) 내에 있을 경우 동작은 정의되지 않습니다. 이 경우 ranges::copy_backward 를 대신 사용할 수 있습니다.
3) 술어 pred true 를 반환하는 요소들만 복사합니다. 복사되는 요소들의 상대적 순서는 유지됩니다. 소스 범위와 대상 범위가 겹치는 경우 동작은 정의되지 않습니다.
2,4) (1,3) 와 동일하지만, r 를 소스 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

목차

매개변수

first, last - 복사할 요소들의 범위 를 정의하는 반복자-감시자 쌍
r - 복사할 요소들의 범위
result - 대상 범위의 시작 지점
pred - 투영된 요소들에 적용할 조건자
proj - 요소들에 적용할 투영

반환값

ranges::in_out_result 를 포함하며, 입력 반복자는 last 와 같고 출력 반복자는 복사된 마지막 요소의 다음을 가리키는 객체입니다.

복잡도

1,2) 정확히 last - first 번의 할당이 수행됩니다.
3,4) 정확히 last - first 번의 술어 및 프로젝션 적용, 0 last - first 번의 할당 사이에서 수행됨 (술어가 true 를 반환하는 모든 요소에 대한 할당, 술어와 입력 데이터에 의존적).

참고 사항

실제로, ranges::copy 구현체는 다중 할당을 피하고 값 타입이 TriviallyCopyable 이고 반복자 타입이 contiguous_iterator 를 만족하는 경우 std::memmove 와 같은 벌크 복사 함수를 사용합니다.

겹치는 범위를 복사할 때, ranges::copy 는 왼쪽으로 복사할 때(대상 범위의 시작이 원본 범위 밖에 있을 때) 적합한 반면, ranges::copy_backward 는 오른쪽으로 복사할 때(대상 범위의 끝이 원본 범위 밖에 있을 때) 적합합니다.

가능한 구현

copy (1)(2)
struct copy_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S, std::weakly_incrementable O>
    requires std::indirectly_copyable<I, O>
    constexpr ranges::copy_result<I, O> operator()(I first, S last, O result) const
    {
        for (; first != last; ++first, (void)++result)
            *result = *first;
        return {std::move(first), std::move(result)};
    }
    template<ranges::input_range R, std::weakly_incrementable O>
    requires std::indirectly_copyable<ranges::iterator_t<R>, O>
    constexpr ranges::copy_result<ranges::borrowed_iterator_t<R>, O>
        operator()(R&& r, O result) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), std::move(result));
    }
};
inline constexpr copy_fn copy;
copy_if (3)(4)
struct 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::copy_if_result<I, O>
        operator()(I first, S last, O result, Pred pred, Proj proj = {}) const
    {
        for (; first != last; ++first)
            if (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::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::ref(pred), std::ref(proj));
    }
};
inline constexpr copy_if_fn copy_if;

예제

다음 코드는 ranges::copy 를 사용하여 하나의 std::vector 내용을 다른 std::vector 로 복사하고 결과를 출력합니다.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
int main()
{
    std::vector<int> source(10);
    std::iota(source.begin(), source.end(), 0);
    std::vector<int> destination;
    std::ranges::copy(source.begin(), source.end(), std::back_inserter(destination));
// 또는 대안으로
//  std::vector<int> destination(source.size());
//  std::ranges::copy(source.begin(), source.end(), destination.begin());
// 두 방법 모두 다음 코드와 동등함
//  std::vector<int> destination = source;
    std::cout << "Destination contains: ";
    std::ranges::copy(destination, std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
    std::cout << "Odd numbers in destination are: ";
    std::ranges::copy_if(destination, std::ostream_iterator<int>(std::cout, " "),
                         [](int x) { return (x % 2) == 1; });
    std::cout << '\n';
}

출력:

Destination contains: 0 1 2 3 4 5 6 7 8 9
Odd numbers in destination are: 1 3 5 7 9

참고 항목

요소 범위를 역순으로 복사합니다
(알고리즘 함수 객체)
뒤집힌 범위의 복사본을 생성합니다
(알고리즘 함수 객체)
지정된 개수의 요소를 새 위치로 복사합니다
(알고리즘 함수 객체)
요소 범위에 특정 값을 할당합니다
(알고리즘 함수 객체)
특정 조건을 만족하는 요소를 제외하고 범위를 복사합니다
(알고리즘 함수 객체)
요소 범위를 새 위치로 복사합니다
(함수 템플릿)