🌍 C++ Study/C++ 기초
C++ std::count string의 문자 갯수 세기 std::count_if
맨텀
2024. 11. 19. 19:30
헤더는 <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; });