💡 퀵 접속: cpp.kr/copy_if
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;
// 짝수만 복사
std::copy_if(source.begin(), source.end(), std::back_inserter(destination),
[](int n) { return n % 2 == 0; });
// 결과 출력
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 6 7 8 복사본 (짝수만): 2 4 6 8
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
std::string source = "Hello, World! 123";
std::string destination;
// 알파벳 문자만 복사
std::copy_if(source.begin(), source.end(), std::back_inserter(destination),
[](char c) { return std::isalpha(c); });
std::cout << "원본: " << source << std::endl;
std::cout << "복사본 (알파벳만): " << destination << std::endl;
return 0;
}
실행 결과:
원본: Hello, World! 123 복사본 (알파벳만): HelloWorld
#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},
{"Eve", 40}
};
std::vector<Person> destination;
// 30세 이상인 사람만 복사
std::copy_if(source.begin(), source.end(), std::back_inserter(destination),
[](const Person& p) { return p.age >= 30; });
// 결과 출력
std::cout << "원본:" << std::endl;
for (const auto& person : source) {
std::cout << person.name << " (" << person.age << "세)" << std::endl;
}
std::cout << "\n복사본 (30세 이상):" << 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세) Eve (40세) 복사본 (30세 이상): Charlie (30세) David (35세) Eve (40세)
| 함수 | 설명 |
|---|---|
| copy_if(first, last, result, pred) | first부터 last까지의 범위에서 pred 조건을 만족하는 요소들을 result부터 시작하는 범위로 복사 |