헤더는 <algorithm> 이며, 벡터, 리스트, 배열, 문자열 등 연속 컨테이너에 대해서 사용할 수 있다.
std::count
컨테이너에서 주어진 값과 일치하는 원소의 갯수를 센다.
string의 경우 주어는 char와 일치하는 문자의 갯수를 샌다.
cppreference : std::count, std::count_if
https://en.cppreference.com/w/cpp/algorithm/count
template<class InputIt, class T>
typename std::iterator_traits<InputIt>::difference_type
count(InputIt first, InputIt last, const T& value);
ex) 주어진 string에 'a' 문자가 몇개나 포함되었는지를 구한다.
int num = std::count(my_string.begin(), my_string.end(), 'a');
std::count_if
컨테이너에서 주어진 델리게이트 조건에 해당하는 갯수를 추출한다.
template< class InputIt, class UnaryPred >
typename std::iterator_traits<InputIt>::difference_type
count_if( InputIt first, InputIt last, UnaryPred p );
ex) 주어진 vector<int>에서 4의 배수가 몇개나 포함되었는지 구한다.
int count_div4 = std::count_if(v.begin(), v.end(), [](int i) { return i % 4 == 0; });
'🌍 C++ Study > C++ 기초' 카테고리의 다른 글
C++ std::distance 이터레이터의 거리 구하기 (0) | 2024.11.20 |
---|---|
C++ vector의 부분 벡터 구하기 (0) | 2024.11.20 |
C++ vector sort 벡터 정렬 algorithm (0) | 2024.11.17 |
C++ string 문자열 뒤집기 std::reverse (0) | 2024.11.16 |
C++ string 부분 문자열 구하기 string::substr (0) | 2024.11.16 |