💡 퀵 접속: cpp.kr/copy_n

copy_n

C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 지정된 개수만큼의 요소를 다른 범위로 복사합니다. 원본 범위는 수정되지 않으며, 복사된 결과는 대상 범위에 저장됩니다.

기본 사용법

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> source = {1, 2, 3, 4, 5, 6, 7, 8};
    std::vector<int> destination(3);
    
    // source의 처음 3개 요소를 destination으로 복사
    std::copy_n(source.begin(), 3, destination.begin());
    
    // 결과 출력
    std::cout << "원본: ";
    for (int n : source) std::cout << n << " ";
    std::cout << std::endl;
    
    std::cout << "복사본 (처음 3개): ";
    for (int n : destination) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

원본: 1 2 3 4 5 6 7 8
복사본 (처음 3개): 1 2 3

문자열 복사

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string source = "Hello, World!";
    std::string destination(5, ' ');  // 5개의 공백으로 초기화
    
    // source의 처음 5개 문자를 destination으로 복사
    std::copy_n(source.begin(), 5, destination.begin());
    
    std::cout << "원본: " << source << std::endl;
    std::cout << "복사본 (처음 5개): " << destination << std::endl;
    
    return 0;
}

실행 결과:

원본: Hello, World!
복사본 (처음 5개): Hello

사용자 정의 타입 복사

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

struct Person {
    std::string name;
    int age;
};

int main() {
    std::vector<Person> source = {
        {"Alice", 20},
        {"Bob", 25},
        {"Charlie", 30},
        {"David", 35}
    };
    std::vector<Person> destination(2);  // 2개의 Person 객체를 저장할 공간
    
    // source의 처음 2개 Person 객체를 destination으로 복사
    std::copy_n(source.begin(), 2, destination.begin());
    
    // 결과 출력
    std::cout << "원본:" << std::endl;
    for (const auto& person : source) {
        std::cout << person.name << " (" << person.age << "세)" << std::endl;
    }
    
    std::cout << "\n복사본 (처음 2개):" << std::endl;
    for (const auto& person : destination) {
        std::cout << person.name << " (" << person.age << "세)" << std::endl;
    }
    
    return 0;
}

실행 결과:

원본:
Alice (20세)
Bob (25세)
Charlie (30세)
David (35세)

복사본 (처음 2개):
Alice (20세)
Bob (25세)

참고사항

  • copy_n은 algorithm 헤더에 정의되어 있습니다.
  • 원본 범위는 수정되지 않습니다.
  • 시간 복잡도는 O(n)입니다 (n은 복사할 요소의 개수).
  • 대상 범위는 복사할 요소의 개수만큼의 공간이 있어야 합니다.
  • copy와 달리 복사할 요소의 개수를 명시적으로 지정합니다.
  • 원본 범위의 크기가 지정된 개수보다 작으면 정의되지 않은 동작이 발생합니다.
  • 부분적인 데이터 복사가 필요할 때 유용합니다.
함수 설명
copy_n(first, count, result) first부터 시작하는 범위에서 count개의 요소를 result부터 시작하는 범위로 복사