Namespaces
Variants

std:: copy, std:: copy_if

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
copy copy_if
(C++11)
(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
헤더 파일에 정의됨 <algorithm>
template < class InputIt, class OutputIt >

OutputIt copy ( InputIt first, InputIt last,

OutputIt d_first ) ;
(1) (C++20부터 constexpr)
template < class ExecutionPolicy,

class ForwardIt1, class ForwardIt2 >
ForwardIt2 copy ( ExecutionPolicy && policy,
ForwardIt1 first, ForwardIt1 last,

ForwardIt2 d_first ) ;
(2) (C++17부터)
template < class InputIt, class OutputIt, class UnaryPred >

OutputIt copy_if ( InputIt first, InputIt last,

OutputIt d_first, UnaryPred pred ) ;
(3) (C++11부터)
(C++20부터 constexpr)
template < class ExecutionPolicy,

class ForwardIt1, class ForwardIt2, class UnaryPred >
ForwardIt2 copy_if ( ExecutionPolicy && policy,
ForwardIt1 first, ForwardIt1 last,

ForwardIt2 d_first, UnaryPred pred ) ;
(4) (C++17부터)

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

1) 범위 [ first , last ) 내의 모든 요소들을 first 부터 시작하여 last 까지 진행하면서 복사합니다.
만약 d_first [ first , last ) 범위 내에 있다면, 동작은 정의되지 않습니다. 이 경우에는 std::copy_backward 를 대신 사용할 수 있습니다.
2) 요소들을 복사하지만, policy 에 따라 실행됩니다.
이 오버로드는 다음의 모든 조건이 만족될 때만 오버로드 해결에 참여합니다:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> true 입니다.

(C++20 이전)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> true 입니다.

(C++20 이후)
만약 [ first , last ) 와 복사 대상 범위가 겹치는 경우, 동작은 정의되지 않습니다.
3) 술어 pred true 를 반환하는 요소들만 복사합니다. 이 복사 알고리즘은 안정적입니다: 복사되는 요소들의 상대적 순서가 유지됩니다.
만약 [ first , last ) 와 복사 대상 범위가 겹치는 경우, 동작은 정의되지 않습니다.
4) (3) 과 동일하지만, policy 에 따라 실행됩니다.
이 오버로드는 다음의 모든 조건이 만족될 때만 오버로드 해결에 참여합니다:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> true 입니다.

(C++20 이전)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> true 입니다.

(C++20 이후)

목차

매개변수

first, last - 복사할 요소들의 소스 범위 를 정의하는 반복자 쌍
d_first - 대상 범위의 시작 지점
policy - 사용할 실행 정책
pred - 필요한 요소에 대해 ​ true 를 반환하는 단항 predicate.

pred ( v ) 표현식은 InputIt 의 값 타입인 VT 의 (const 가능성 있는) 모든 타입 인수 v 에 대해 bool 로 변환 가능해야 하며, 값 범주 와 관계없이 v 를 수정해서는 안 됩니다. 따라서 VT & 매개변수 타입은 허용되지 않으며 , VT 에 대해 이동이 복사와 동등하지 않는 한 VT 타입도 허용되지 않습니다 (C++11부터) . ​

타입 요구사항
-
InputIt LegacyInputIterator 요구사항을 충족해야 합니다.
-
OutputIt LegacyOutputIterator 요구사항을 충족해야 합니다.
-
ForwardIt1, ForwardIt2 LegacyForwardIterator 요구사항을 충족해야 합니다.
-
UnaryPred Predicate 요구사항을 충족해야 합니다.

반환값

대상 범위에서 복사된 요소의 한 요소 너머에 위치한 출력 반복자입니다.

복잡도

주어진 N std:: distance ( first, last ) 인 경우:

1,2) 정확히 N 번의 할당.
3,4) 정확히 N 번의 predicate 적용과 최대 N 번의 할당.

ExecutionPolicy 를 사용하는 오버로드의 경우, ForwardIt1 의 값 타입이 MoveConstructible 가 아닐 때 성능 저하가 발생할 수 있습니다.

예외

ExecutionPolicy 라는 템플릿 매개변수를 가진 오버로드는 다음과 같이 오류를 보고합니다:

  • 알고리즘의 일부로 호출된 함수 실행 중 예외가 발생하고 ExecutionPolicy 표준 정책 중 하나인 경우, std::terminate 가 호출됩니다. 다른 ExecutionPolicy 의 경우 동작은 구현에 따라 정의됩니다.
  • 알고리즘이 메모리 할당에 실패하는 경우, std::bad_alloc 이 throw됩니다.

가능한 구현

copy (1)
template<class InputIt, class OutputIt>
OutputIt copy(InputIt first, InputIt last,
              OutputIt d_first)
{
    for (; first != last; (void)++first, (void)++d_first)
        *d_first = *first;
    return d_first;
}
copy_if (3)
template<class InputIt, class OutputIt, class UnaryPred>
OutputIt copy_if(InputIt first, InputIt last,
                 OutputIt d_first, UnaryPred pred)
{
    for (; first != last; ++first)
        if (pred(*first))
        {
            *d_first = *first;
            ++d_first;
        }
    return d_first;
}

참고 사항

실제로, std::copy 구현체는 여러 번의 할당을 피하고 값 타입이 TriviallyCopyable 이고 반복자 타입이 LegacyContiguousIterator 를 만족하는 경우 std::memmove 와 같은 대량 복사 함수를 사용합니다.

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

예제

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

#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
int main()
{
    std::vector<int> from_vector(10);
    std::iota(from_vector.begin(), from_vector.end(), 0);    
    std::vector<int> to_vector;
    std::copy(from_vector.begin(), from_vector.end(), std::back_inserter(to_vector));
// 또는 다른 방법으로,
//  std::vector<int> to_vector(from_vector.size());
//  std::copy(from_vector.begin(), from_vector.end(), to_vector.begin());
// 두 방법 모두 다음과 동일합니다
//  std::vector<int> to_vector = from_vector;
    std::cout << "to_vector contains: ";
    std::copy(to_vector.begin(), to_vector.end(),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
    std::cout << "odd numbers in to_vector are: ";
    std::copy_if(to_vector.begin(), to_vector.end(),
                 std::ostream_iterator<int>(std::cout, " "),
                 [](int x) { return x % 2 != 0; });
    std::cout << '\n';
    std::cout << "to_vector contains these multiples of 3: ";
    to_vector.clear();
    std::copy_if(from_vector.begin(), from_vector.end(),
                 std::back_inserter(to_vector),
                 [](int x) { return x % 3 == 0; });
    for (const int x : to_vector)
        std::cout << x << ' ';
    std::cout << '\n';
}

가능한 출력:

to_vector contains: 0 1 2 3 4 5 6 7 8 9
odd numbers in to_vector are: 1 3 5 7 9
to_vector contains these multiples of 3: 0 3 6 9

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 2039 C++11 std::copy_if 의 반환 값이 명시되지 않음 명시됨
LWG 2044 C++11 std::copy_if 의 안정성이 정의되지 않음 정의됨

참고 항목

요소 범위를 역순으로 복사합니다
(function template)
뒤집힌 범위의 사본을 생성합니다
(function template)
(C++11)
지정된 개수의 요소를 새 위치로 복사합니다
(function template)
지정된 값을 범위의 모든 요소에 복사 할당합니다
(function template)
특정 조건을 만족하는 요소를 생략하고 요소 범위를 복사합니다
(function template)
요소 범위를 새 위치로 복사합니다
(algorithm function object)