count_if는 <algorithm> 헤더에 포함된 함수로, 특정 조건을 만족하는 요소의 개수를 계산할 때 사용된다.
template<class InputIterator, class Predicate>
typename iterator_traits<InputIterator>::difference_type
count_if(InputIterator first, InputIterator last, Predicate pred);
매개변수:
first : 탐색을 시작할 반복자last : 탐색을 종료할 반복자pred : 조건을 정의하는 함수 또는 람다 표현식반환값:
bool을 반환해야되고, 요소가 조건을 만족하면 true, 아니면 false를 반환한다.std::vector, std::list, std::array 등)에 사용할 수 있다.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