💡 퀵 접속: cpp.kr/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(first, last, pred) | 주어진 범위에서 pred 조건을 만족하는 요소의 개수를 반환 |