💡 퀵 접속: cpp.kr/copy

copy

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

기본 사용법

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

int main() {
    std::vector<int> source = {1, 2, 3, 4, 5};
    std::vector<int> destination(source.size());
    
    // source의 모든 요소를 destination으로 복사
    std::copy(source.begin(), source.end(), destination.begin());
    
    // 결과 출력
    std::cout << "원본: ";
    for (int n : source) std::cout << n << " ";
    std::cout << std::endl;
    
    std::cout << "복사본: ";
    for (int n : destination) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

원본: 1 2 3 4 5
복사본: 1 2 3 4 5

문자열 복사

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

int main() {
    std::string source = "Hello, World!";
    std::string destination(source.size(), ' ');
    
    // source의 모든 문자를 destination으로 복사
    std::copy(source.begin(), source.end(), destination.begin());
    
    std::cout << "원본: " << source << std::endl;
    std::cout << "복사본: " << destination << std::endl;
    
    return 0;
}

실행 결과:

원본: Hello, World!
복사본: Hello, World!

사용자 정의 타입 복사

#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}
    };
    std::vector<Person> destination(source.size());
    
    // source의 모든 Person 객체를 destination으로 복사
    std::copy(source.begin(), source.end(), destination.begin());
    
    // 결과 출력
    std::cout << "원본:" << std::endl;
    for (const auto& person : source) {
        std::cout << person.name << " (" << person.age << "세)" << std::endl;
    }
    
    std::cout << "\n복사본:" << std::endl;
    for (const auto& person : destination) {
        std::cout << person.name << " (" << person.age << "세)" << std::endl;
    }
    
    return 0;
}

실행 결과:

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

복사본:
Alice (20세)
Bob (25세)
Charlie (30세)

참고사항

  • copy는 algorithm 헤더에 정의되어 있습니다.
  • 원본 범위는 수정되지 않습니다.
  • 시간 복잡도는 O(n)입니다 (n은 범위의 크기).
  • 대상 범위는 원본 범위와 크기가 같거나 더 커야 합니다.
  • copy_if는 조건을 만족하는 요소만 복사하는 버전입니다.
  • copy_n은 n개의 요소를 복사하는 버전입니다.
  • copy_backward는 역방향으로 복사하는 버전입니다.
  • 원본 데이터를 유지하면서 복사본이 필요할 때 유용합니다.
함수 설명
copy(first, last, d_first) 주어진 범위의 요소들을 d_first부터 시작하는 범위로 복사