cpp/algorithm/count if
提供:cppreference.com
11/13/2010 04:35
目次 |
[編集] count_if
#include <algorithm> template< class InputIterator, class UnaryPredicate > typename iterator_traits<InputIterator>::difference_type count_if( InputIterator first, InputIterator last, UnaryPredicate p );
範囲内で述語pがtrueとなる要素数を返す。
[編集] Parameters
first, last - 検査する要素の範囲
p - 単項述語
[編集] Return value
述語がtrueとなる要素数
[編集] Equivalent function
template<class InputIterator, class UnaryPredicate> typename iterator_traits<InputIterator>::difference_type UnaryFunction count(InputIterator first, InputIterator last, UnaryPredicate p) { typename iterator_traits<InputIterator>::difference_type ret = 0; for (; first != last; ++first) { if (p(*first)) { ret++; } } return ret; }
[編集] Example
例えば次のコードのような、整数3の場合にtrueを返す述語を渡されたcount_ifは、 配列内の3と等しい要素数を数える:
int nums[] = { 0, 1, 2, 3, 4, 5, 9, 3, 13 }; int start = 0; int end = 9; int target_value = 3; int num_items = count_if(nums, nums+end, bind2nd(equal_to<int>(), target_value)); std::cout << "nums[] contains " << num_items << " items matching " << target_value;
出力:
nums[] contains 2 items matching 3
[編集] Complexity
"first"と"last"の間の距離は線形