count_if function template
template <class InputIterator, class UnaryPredicate>
typename iterator_traits<InputIterator>::difference_type
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
Returns the number of elements within a range satisfying the condition
Number of elements in the range of return values [first,last)
for which pred is true.
The behavior of this function template is equivalent to:
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;
}
parameter
First, last
The input iterator to the initial position and the final position of the element of the sequence. Range is used [first,last)
, it contains all the elements of the first and the last, the last comprising a first member, but not the pointed element pointing.
Expected value
Unary function accepts as a parameter in the range of elements, and can be converted to the return value bool
. The value returned indicates whether this function computation elements.
This function may not modify its parameters.
This function may be a function or pointer to the object.
return value
The number of elements in a range [first,last)
not return for which the PRED false
.
Return type ( iterator_traits
Case
// count_if example
#include <iostream> // std::cout
#include <algorithm> // std::count_if
#include <vector> // std::vector
bool 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 9
int mycount = count_if (myvector.begin(), myvector.end(), IsOdd);
std::cout << "myvector contains " << mycount << " odd values.\n";
return 0;
}
myvector包含5个奇数值。
complex
Between the first and last from linear: pred called once for each element.
Data contest
[first,last)
Access the range of objects (each object only visited once).
exception
Pre throw throw throw or throwing any operations on iterators.
Please note that the invalid parameters can lead to undefined 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 ) |