Movatterモバイル変換


[0]ホーム

URL:


cplusplus.com

Reference

<algorithm>

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 toval.

The function usesoperator== to compare the individual elements toval.

The behavior of this function template is equivalent to:
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;}

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.
val
Value to match.
T shall be a type supporting comparisons with the elements pointed byInputIterator usingoperator== (with the elements as left-hand side operands, andval as right-hand side).

Return value

The number of elements in the range[first,last) that compare equal toval.
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
17
18
// count algorithm example#include <iostream>// std::cout#include <algorithm>// std::count#include <vector>// std::vectorint main () {// counting elements in array:int myints[] = {10,20,30,30,20,10,10,20};// 8 elementsint 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;}

Output:
10 appears 3 times.20 appears 3 times.


Complexity

Linear in thedistance betweenfirst andlast: Compares once each element.

Data races

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

Exceptions

Throws if either an element comparison or an operation on an iterator throws.
Note that invalid arguments causeundefined behavior.

See also

for_each
Apply function to range(function template)
count_if
Return number of elements in range satisfying condition(function template)
find
Find value in range(function template)
replace
Replace 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