algorithm_copy_n

algorithm_copy_n (N개 복사)

std::copy_n은 소스 범위의 처음 count개 요소를 목적지 범위로 복사해요. 복사할 개수를 명시적으로 지정하는 점이 std::copy와 달라요.

출처: cppreference

본문

std::copy_n<algorithm> 헤더에 정의되어 있어요. count가 양수이면 소스 범위 [first, std::next(first, count))의 모든 요소를 목적지 범위 [d_first, std::next(d_first, count))로 복사해요.

template< class InputIt, class Size, class OutputIt >
OutputIt copy_n( InputIt first, Size count, OutputIt d_first );

count가 양수가 아니면 아무것도 하지 않아요. 소스와 목적지 범위는 겹칠 수 있지만, 그 경우 결과의 순서는 예측할 수 없어요. 병렬 실행 정책을 받는 오버로드도 있어요.

매개변수 (Parameters)

  • first — 소스 범위의 시작
  • count — 복사할 요소의 개수
  • d_first — 목적지 범위의 시작

반환값 (Return value)

목적지 범위의 끝(past-the-end) 반복자예요. count가 양수가 아니면 d_first를 돌려줘요.

복잡도 (Complexity)

정확히 max(count, 0)번의 배정이 필요해요.

예제 (Example)

#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <string>
#include <vector>

int main()
{
    std::string in {"1234567890"};
    std::string out;
    std::copy_n(in.begin(), 4, std::back_inserter(out));
    std::cout << out << '\n';

    std::vector<int> v_in(128);
    std::iota(v_in.begin(), v_in.end(), 1);
    std::vector<int> v_out(v_in.size());
    std::copy_n(v_in.cbegin(), 100, v_out.begin());
    std::cout << std::accumulate(v_out.begin(), v_out.end(), 0) << '\n';
}

출력:

1234
5050

가능한 구현 (Possible implementation)

template<class InputIt, class Size, class OutputIt>
constexpr //< since C++20
OutputIt copy_n(InputIt first, Size count, OutputIt d_first)
{
    if (count > 0)
    {
        *d_first = *first;
        ++d_first;
        for (Size i = 1; i != count; ++i, (void)++d_first)
            *d_first = *++first;
    }
    return d_first;
}

더 알아보기 (Learn more)

cppreference