💡 퀵 접속: cpp.kr/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(first, last, d_first) | 주어진 범위의 요소들을 d_first부터 시작하는 범위로 복사 |