-
std::count_if프로그래밍 언어/C++ 2024. 7. 23. 16:07
std::count_if는 C++ 표준 라이브러리의 <algorithm> 헤더에 정의된 함수 템플릿입니다. 이 함수는 범위 내에서 특정 조건을 만족하는 요소의 개수를 세는 데 사용됩니다. std::count_if는 조건을 지정하는 데 사용하는 함수 또는 함수 객체를 매개변수로 받아들입니다.
사용 사례:
#include <algorithm> #include <vector> #include <iostream> int main() { std::vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // 짝수의 개수를 세기 위한 람다 함수 auto is_even = [](int n) { return n % 2 == 0; }; // std::count_if를 사용하여 조건을 만족하는 요소의 개수를 셈 int count = std::count_if(vec.begin(), vec.end(), is_even); std::cout << "Number of even elements: " << count << std::endl; return 0; }
함수 시그니처:
template< class InputIt, class UnaryPredicate > typename std::iterator_traits<InputIt>::difference_type count_if( InputIt first, InputIt last, UnaryPredicate p );
'프로그래밍 언어 > C++' 카테고리의 다른 글
싱글턴 패턴 적용 (0) 2024.08.21 사용자 정의 리터럴(literal) (1) 2024.07.23 std::tie (1) 2024.07.23 C++17 구조화된 바인딩(structured bindings) (0) 2024.07.23 생성자 이니셜라이저(initializer list) (0) 2024.07.23