💡 퀵 접속: cpp.kr/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(first, last, d_last) | first부터 last까지의 범위의 요소들을 d_last부터 역방향으로 복사 |