💡 퀵 접속: cpp.kr/copy_backward

copy_backward

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

기본 사용법

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

int main() {
    std::vector<int> source = {1, 2, 3, 4, 5};
    std::vector<int> destination(5);
    
    // source의 요소들을 destination으로 역방향 복사
    std::copy_backward(source.begin(), source.end(), destination.end());
    
    // 결과 출력
    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 <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8};
    
    // 벡터의 중간 부분을 오른쪽으로 한 칸 이동
    std::copy_backward(numbers.begin() + 2, numbers.begin() + 5, numbers.begin() + 6);
    
    std::cout << "이동 후: ";
    for (int n : numbers) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

이동 후: 1 2 3 3 4 5 7 8

사용자 정의 타입 복사

#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(3);
    
    // source의 Person 객체들을 destination으로 역방향 복사
    std::copy_backward(source.begin(), source.end(), destination.end());
    
    // 결과 출력
    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_backward는 algorithm 헤더에 정의되어 있습니다.
  • 원본 범위는 수정되지 않습니다.
  • 시간 복잡도는 O(n)입니다 (n은 범위의 크기).
  • 대상 범위는 원본 범위와 크기가 같거나 더 커야 합니다.
  • copy와 달리 역방향으로 복사하므로, 원본과 대상 범위가 겹칠 때 안전하게 사용할 수 있습니다.
  • 대상 범위의 끝 위치를 지정해야 합니다 (copy는 시작 위치를 지정).
  • 원본과 대상 범위가 겹치는 경우에 특히 유용합니다.
함수 설명
copy_backward(first, last, d_last) first부터 last까지의 범위의 요소들을 d_last부터 역방향으로 복사