count_if

김민수·2025년 1월 23일

C++

목록 보기
62/68

count_if<algorithm> 헤더에 포함된 함수로, 특정 조건을 만족하는 요소의 개수를 계산할 때 사용된다.


1. 함수 정의

template<class InputIterator, class Predicate>
typename iterator_traits<InputIterator>::difference_type
count_if(InputIterator first, InputIterator last, Predicate pred);
  • 매개변수:

    • first : 탐색을 시작할 반복자
    • last : 탐색을 종료할 반복자
    • pred : 조건을 정의하는 함수 또는 람다 표현식
  • 반환값:

    • 조건을 만족하는 요소의 개수를 반환


2. 특징

  1. Predicate: 조건을 정의하는 함수 또는 람다 표현식이다.
    • bool을 반환해야되고, 요소가 조건을 만족하면 true, 아니면 false를 반환한다.
  2. 범용성: 모든 반복 가능한 컨테이너(std::vector, std::list, std::array 등)에 사용할 수 있다.
  3. 읽기 전용: 함수 내부에서 요소를 수정하지 않는다.


3. 사용 예시

1) 기본 사용

#include <iostream>
#include <vector>
#include <algorithm> // count_if 함수 포함

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    // 조건: 홀수인 요소 개수 세기
    int odd_count = std::count_if(numbers.begin(), numbers.end(), [](int n) {
        return n % 2 != 0;
    });

    std::cout << "홀수의 개수: " << odd_count << std::endl;

    return 0;
}

출력:

홀수의 개수: 5

2) 문자열 조건으로 필터링

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

int main() {
    std::vector<std::string> words = {"apple", "banana", "cherry", "date", "egg"};

    // 조건: 길이가 5 이상인 문자열 개수
    int count = std::count_if(words.begin(), words.end(), [](const std::string& word) {
        return word.length() >= 5;
    });

    std::cout << "길이가 5 이상인 단어의 개수: " << count << std::endl;

    return 0;
}

출력:

길이가 5 이상인 단어의 개수: 3

3) 사용자 정의 함수로 조건 정의

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

bool isGreaterThanFive(int n) {
    return n > 5;
}

int main() {
    std::vector<int> numbers = {1, 4, 6, 8, 10};

    // 조건: 5보다 큰 숫자 개수
    int count = std::count_if(numbers.begin(), numbers.end(), isGreaterThanFive);

    std::cout << "5보다 큰 숫자의 개수: " << count << std::endl;

    return 0;
}

출력:

5보다 큰 숫자의 개수: 3
profile
안녕하세요

0개의 댓글