💡 퀵 접속: cpp.kr/count_if

count_if

C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 특정 조건을 만족하는 요소의 개수를 반환합니다. 조건은 단항 술어 함수로 지정됩니다.

기본 사용법

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

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    // 짝수의 개수 세기
    int even_count = std::count_if(numbers.begin(), numbers.end(),
                                  [](int n) { return n % 2 == 0; });
    std::cout << "짝수의 개수: " << even_count << std::endl;
    
    // 5보다 큰 수의 개수 세기
    int greater_than_five = std::count_if(numbers.begin(), numbers.end(),
                                         [](int n) { return n > 5; });
    std::cout << "5보다 큰 수의 개수: " << greater_than_five << std::endl;
    
    return 0;
}

실행 결과:

짝수의 개수: 5
5보다 큰 수의 개수: 5

문자열에서 사용

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

int main() {
    std::string text = "Hello, World! 123";
    
    // 대문자의 개수 세기
    int upper_count = std::count_if(text.begin(), text.end(),
                                   [](char c) { return std::isupper(c); });
    std::cout << "대문자의 개수: " << upper_count << std::endl;
    
    // 숫자의 개수 세기
    int digit_count = std::count_if(text.begin(), text.end(),
                                   [](char c) { return std::isdigit(c); });
    std::cout << "숫자의 개수: " << digit_count << std::endl;
    
    return 0;
}

실행 결과:

대문자의 개수: 2
숫자의 개수: 3

사용자 정의 타입에서 사용

#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세 이상인 사람의 수 세기
    int over_thirty = std::count_if(people.begin(), people.end(),
                                   [](const Person& p) { return p.age >= 30; });
    std::cout << "30세 이상인 사람의 수: " << over_thirty << std::endl;
    
    // 이름이 'A'로 시작하는 사람의 수 세기
    int starts_with_a = std::count_if(people.begin(), people.end(),
                                     [](const Person& p) { return p.name[0] == 'A'; });
    std::cout << "이름이 'A'로 시작하는 사람의 수: " << starts_with_a << std::endl;
    
    return 0;
}

실행 결과:

30세 이상인 사람의 수: 3
이름이 'A'로 시작하는 사람의 수: 1

참고사항

  • count_if는 algorithm 헤더에 정의되어 있습니다.
  • 단항 술어 함수를 사용하여 조건을 지정합니다.
  • 시간 복잡도는 O(n)입니다.
  • 범위가 비어있으면 0을 반환합니다.
  • 조건에 맞는 요소의 개수를 세는 데 유용합니다.
  • count와 함께 사용하여 다양한 방식으로 요소의 개수를 셀 수 있습니다.
  • 반환 타입은 반복자의 차이 타입입니다 (일반적으로 std::ptrdiff_t).
  • 람다 함수를 사용하여 조건을 간단하게 정의할 수 있습니다.
함수 설명
count_if(first, last, pred) 주어진 범위에서 pred 조건을 만족하는 요소의 개수를 반환