copy
copy (복사) / copy_if (조건부 복사)
소스 범위의 원소를 목적지 범위로 복사하는 알고리즘이에요. copy는 전체를, copy_if는 조건을 만족하는 것만 복사해요. <algorithm> 헤더에 있어요.
출처: cppreference
본문
copy는 범위 [first, last)의 원소를 d_first부터 순서대로 복사해요. 반환 값은 마지막으로 복사된 원소 다음을 가리키는 d_first + (last - first)예요.
template< class InputIt, class OutputIt >
OutputIt copy( InputIt first, InputIt last,
OutputIt d_first ); // (1)
template< class InputIt, class OutputIt, class UnaryPred >
OutputIt copy_if( InputIt first, InputIt last,
OutputIt d_first, UnaryPred pred ); // (2)
-
copy:[first, last)전체를 복사해요.
-
copy_if: 술어pred가 참인 원소만 복사해요. 복사 순서는 유지돼요.
C++17부터 실행 정책을 받는 병렬 오버로드가 추가됐어요.
중요한 규칙: 소스와 목적지 범위가 겹치면 안 돼요. 겹치는 경우에는 copy_backward를 쓰거나 대상을 잘못 맞추지 않도록 주의해야 해요. 특히 d_first가 소스 범위 안에 있으면 미정의 동작이 돼요.
std::vector<int> src{1, 2, 3, 4, 5};
std::vector<int> dst(5);
std::copy(src.begin(), src.end(), dst.begin());
// 짝수만 복사
std::copy_if(src.begin(), src.end(), dst.begin(),
[](int x){ return x % 2 == 0; });
copy는 memcpy처럼 빠르게 동작하는 최적화 경로가 있어서, POD 타입 복사에 자주 쓰여요. 조건부 복사가 필요하면 copy_if를 쓰면 돼요.