algorithm_count
algorithm_count (요소 개수 세기)
std::count는 범위에서 특정 값과 같은 요소의 개수를 세고, std::count_if는 단항 술어를 만족하는 요소의 개수를 세요.
출처: cppreference
본문
std::count와 std::count_if는 소스 범위 [first, last)에서 지정한 기준을 만족하는 요소의 개수를 돌려줘요. <algorithm> 헤더에 정의되어 있어요.
template< class InputIt, class T >
typename std::iterator_traits<InputIt>::difference_type
count( InputIt first, InputIt last, const T& value );
template< class InputIt, class UnaryPred >
typename std::iterator_traits<InputIt>::difference_type
count_if( InputIt first, InputIt last, UnaryPred p );
count—*iter == value가 참인 요소의 개수를 세요 (operator==사용).count_if—p(*iter) != false가 참인 요소의 개수를 세요.
병렬 실행 정책을 받는 오버로드도 있어요.
반환값 (Return value)
소스 범위에서 조건을 만족하는 반복자 iter의 개수예요.
복잡도 (Complexity)
N을 std::distance(first, last)라고 하면 count는 정확히 N번 비교하고, count_if는 정확히 N번 p를 적용해요.
예제 (Example)
#include <algorithm>
#include <array>
#include <cassert>
#include <complex>
#include <iostream>
#include <iterator>
int main()
{
constexpr std::array v{1, 2, 3, 4, 4, 3, 7, 8, 9, 10};
std::cout << "v: ";
std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
// Determine how many integers match a target value.
for (const int target : {3, 4, 5})
{
const int num_items = std::count(v.cbegin(), v.cend(), target);
std::cout << "number: " << target << ", count: " << num_items << '\n';
}
// Use a lambda expression to count elements divisible by 4.
int count_div4 = std::count_if(v.begin(), v.end(), [](int i) { return i % 4 == 0; });
std::cout << "numbers divisible by four: " << count_div4 << '\n';
}
출력:
v: 1 2 3 4 4 3 7 8 9 10
number: 3, count: 2
number: 4, count: 2
number: 5, count: 0
numbers divisible by four: 3
가능한 구현 (Possible implementation)
template<class InputIt, class T = typename std::iterator_traits<InputIt>::value_type>
typename std::iterator_traits<InputIt>::difference_type
count(InputIt first, InputIt last, const T& value)
{
typename std::iterator_traits<InputIt>::difference_type ret = 0;
for (; first != last; ++first)
if (*first == value)
++ret;
return ret;
}
template<class InputIt, class UnaryPred>
typename std::iterator_traits<InputIt>::difference_type
count_if(InputIt first, InputIt last, UnaryPred p)
{
typename std::iterator_traits<InputIt>::difference_type ret = 0;
for (; first != last; ++first)
if (p(*first))
++ret;
return ret;
}