function template
<algorithm>
std::count
template <class InputIterator, class T> typename iterator_traits<InputIterator>::difference_type count (InputIterator first, InputIterator last, const T& val);
Count appearances of value in range
Returns the number of elements in the range [first,last)
that compare equal to val.
该函数使用 operator==
将单个元素与 val 进行比较。
此函数模板的行为等同于
1 2 3 4 5 6 7 8 9 10 11
|
template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count (InputIterator first, InputIterator last, const T& val)
{
typename iterator_traits<InputIterator>::difference_type ret = 0;
while (first!=last) {
if (*first == val) ++ret;
++first;
}
return ret;
}
|
参数
- 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 between first and last, including the element pointed by first but not the element pointed by last.
- val
- Value to match.
T shall be a type supporting comparisons with the elements pointed by InputIterator using operator==
(with the elements as left-hand side operands, and val as right-hand side).
返回值
The number of elements in the range [first,last)
that compare equal to val.
The return type (iterator_traits<InputIterator>::difference_type) is a signed integral type.
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
// count algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::count
#include <vector> // std::vector
int main () {
// counting elements in array:
int myints[] = {10,20,30,30,20,10,10,20}; // 8 elements
int mycount = std::count (myints, myints+8, 10);
std::cout << "10 appears " << mycount << " times.\n";
// counting elements in container:
std::vector<int> myvector (myints, myints+8);
mycount = std::count (myvector.begin(), myvector.end(), 20);
std::cout << "20 appears " << mycount << " times.\n";
return 0;
}
|
输出
10 appears 3 times.
20 appears 3 times.
|
复杂度
Linear in the distance between first and last: Compares once each element.
数据竞争
范围 [first,last)
中的对象将被访问(每个对象恰好访问一次)。
异常
如果元素比较或迭代器操作引发异常,则抛出。
请注意,无效参数会导致未定义行为。
另见
- for_each
- 将函数应用于范围 (函数模板)
- count_if
- Return number of elements in range satisfying condition (function template)
- find
- 在范围中查找值 (函数模板)
- replace
- 替换范围中的值 (函数模板)