Movatterモバイル変換


[0]ホーム

URL:


cplusplus.com

Reference

<algorithm>

function template
<algorithm>

std::count_if

template <class InputIterator, class UnaryPredicate>  typename iterator_traits<InputIterator>::difference_type    count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
Return number of elements in range satisfying condition
Returns the number of elements in the range[first,last) for whichpred is true.

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
9
10
11
template <class InputIterator,class UnaryPredicate>typename iterator_traits<InputIterator>::difference_type    count_if (InputIterator first, InputIterator last, UnaryPredicate pred){typename iterator_traits<InputIterator>::difference_type ret = 0;while (first!=last) {if (pred(*first)) ++ret;    ++first;  }return ret;}

Parameters

first, last
Input iterators to the initial and final positions of the sequence of elements. The range used is[first,last), which contains all the elements betweenfirst andlast, including the element pointed byfirst but not the element pointed bylast.
pred
Unary function that accepts an element in the range as argument, and returns a value convertible tobool. The value returned indicates whether the element is counted by this function.
The function shall not modify its argument.
This can either be a function pointer or a function object.

Return value

The number of elements in the range[first,last) for whichpred does not returnfalse.
The return type (iterator_traits<InputIterator>::difference_type) is a signed integral type.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// count_if example#include <iostream>// std::cout#include <algorithm>// std::count_if#include <vector>// std::vectorbool IsOdd (int i) {return ((i%2)==1); }int main () {  std::vector<int> myvector;for (int i=1; i<10; i++) myvector.push_back(i);// myvector: 1 2 3 4 5 6 7 8 9int mycount = count_if (myvector.begin(), myvector.end(), IsOdd);  std::cout <<"myvector contains " << mycount  <<" odd values.\n";return 0;}

Output:
myvector contains 5 odd values.


Complexity

Linear in thedistance betweenfirst andlast: Callspred once for each element.

Data races

The objects in the range[first,last) are accessed (each object is accessed exactly once).

Exceptions

Throws ifpred throws or if any of the operations on iterators throws.
Note that invalid arguments causeundefined behavior.

See also

count
Count appearances of value in range(function template)
for_each
Apply function to range(function template)
find
Find value in range(function template)
Home page |Privacy policy
© cplusplus.com, 2000-2025 - All rights reserved -v3.3.4s
Spotted an error? contact us

[8]ページ先頭

©2009-2026 Movatter.jp