💡 퀵 접속: cpp.kr/copy_if

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는 algorithm 헤더에 정의되어 있습니다.
  • 원본 범위는 수정되지 않습니다.
  • 시간 복잡도는 O(n)입니다 (n은 범위의 크기).
  • 조건을 만족하는 요소만 복사되므로, 대상 범위의 크기는 원본 범위보다 작거나 같을 수 있습니다.
  • back_inserter를 사용하면 대상 컨테이너의 크기를 자동으로 조정할 수 있습니다.
  • 조건부 데이터 복사가 필요할 때 유용합니다.
  • 조건은 단항 술어 함수(unary predicate)로 지정합니다.
함수 설명
copy_if(first, last, result, pred) first부터 last까지의 범위에서 pred 조건을 만족하는 요소들을 result부터 시작하는 범위로 복사