💡 퀵 접속: cpp.kr/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(first, count, result) | first부터 시작하는 범위에서 count개의 요소를 result부터 시작하는 범위로 복사 |