💡 퀵 접속: cpp.kr/find_if

find_if

C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 특정 조건을 만족하는 첫 번째 요소를 찾습니다. 조건은 단항 술어 함수로 제공되며, 조건을 만족하는 첫 번째 요소의 반복자를 반환합니다.

기본 사용법

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    // 짝수 찾기
    auto it1 = std::find_if(v.begin(), v.end(),
        [](int n) { return n % 2 == 0; });
    
    if (it1 != v.end()) {
        std::cout << "첫 번째 짝수를 찾았습니다: " << *it1 << std::endl;
    } else {
        std::cout << "짝수를 찾지 못했습니다." << std::endl;
    }
    
    // 5보다 큰 수 찾기
    auto it2 = std::find_if(v.begin(), v.end(),
        [](int n) { return n > 5; });
    
    if (it2 != v.end()) {
        std::cout << "5보다 큰 첫 번째 수를 찾았습니다: " << *it2 << std::endl;
    } else {
        std::cout << "5보다 큰 수를 찾지 못했습니다." << std::endl;
    }
    
    return 0;
}

실행 결과:

첫 번째 짝수를 찾았습니다: 2
5보다 큰 첫 번째 수를 찾았습니다: 6

문자열에서 사용

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

int main() {
    std::string str = "Hello, World!";
    
    // 대문자 찾기
    auto it1 = std::find_if(str.begin(), str.end(),
        [](char c) { return std::isupper(c); });
    
    if (it1 != str.end()) {
        std::cout << "첫 번째 대문자를 찾았습니다: " << *it1 << std::endl;
    } else {
        std::cout << "대문자를 찾지 못했습니다." << std::endl;
    }
    
    // 공백 찾기
    auto it2 = std::find_if(str.begin(), str.end(),
        [](char c) { return std::isspace(c); });
    
    if (it2 != str.end()) {
        std::cout << "첫 번째 공백을 찾았습니다. 위치: " 
                  << std::distance(str.begin(), it2) << std::endl;
    } else {
        std::cout << "공백을 찾지 못했습니다." << std::endl;
    }
    
    return 0;
}

실행 결과:

첫 번째 대문자를 찾았습니다: H
첫 번째 공백을 찾았습니다. 위치: 5

사용자 정의 타입에서 사용

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

struct Person {
    std::string name;
    int age;
};

int main() {
    std::vector<Person> people = {
        {"Alice", 20},
        {"Bob", 25},
        {"Charlie", 30},
        {"David", 35},
        {"Eve", 40}
    };
    
    // 30세 이상인 사람 찾기
    auto it1 = std::find_if(people.begin(), people.end(),
        [](const Person& p) { return p.age >= 30; });
    
    if (it1 != people.end()) {
        std::cout << "30세 이상인 첫 번째 사람을 찾았습니다: " 
                  << it1->name << " (" << it1->age << "세)" << std::endl;
    } else {
        std::cout << "30세 이상인 사람을 찾지 못했습니다." << std::endl;
    }
    
    // 이름이 'B'로 시작하는 사람 찾기
    auto it2 = std::find_if(people.begin(), people.end(),
        [](const Person& p) { return p.name[0] == 'B'; });
    
    if (it2 != people.end()) {
        std::cout << "이름이 'B'로 시작하는 첫 번째 사람을 찾았습니다: " 
                  << it2->name << std::endl;
    } else {
        std::cout << "이름이 'B'로 시작하는 사람을 찾지 못했습니다." << std::endl;
    }
    
    return 0;
}

실행 결과:

30세 이상인 첫 번째 사람을 찾았습니다: Charlie (30세)
이름이 'B'로 시작하는 첫 번째 사람을 찾았습니다: Bob

참고사항

  • find_if는 algorithm 헤더에 정의되어 있습니다.
  • 단항 술어 함수를 사용하여 조건을 정의합니다.
  • 시간 복잡도는 O(n)입니다 (n은 검색할 범위의 크기).
  • 조건을 만족하는 요소를 찾지 못하면 범위의 끝 반복자를 반환합니다.
  • 첫 번째로 조건을 만족하는 요소의 반복자를 반환합니다.
  • 모든 조건을 만족하는 요소를 찾으려면 find_if를 반복적으로 호출해야 합니다.
  • 정렬된 범위에서는 binary_search나 lower_bound를 사용하는 것이 더 효율적일 수 있습니다.
함수 설명
find_if(first, last, pred) 주어진 범위에서 조건을 만족하는 첫 번째 요소를 찾음