Defined in header <algorithm> | ||||
---|---|---|---|---|
| (1) | |||
| (2) |
Returns the number of elements in the range [first, last)
satisfying specific criteria. The first version counts the elements that are equal to value
, the second version counts elements for which predicate p
returns true
.
Parameters
first, last | - | the range of elements to examine |
value | - | the value to search for |
p | - | unary predicate which returns true for the required elements. The signature of the predicate function should be equivalent to the following:
The signature does not need to have |
Type requirements | ||
- InputIt must meet the requirements of InputIterator . |
Return value
number of elements satisfying the condition.
Complexity
exactly last
- first
comparisons / applications of the predicate.
Notes
For the number of elements in the range [first, last)
without any additional criteria, see std::distance
.
Possible implementation
First version | ||
---|---|---|
| ||
Second version | ||
|
Example
The following code uses count
to determine how many integers in a std::vector
match a target value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <algorithm> #include <iostream> #include <vector> int main() { int data[] = { 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }; std::vector< int > v(data, data+10); int target1 = 3; int target2 = 5; int num_items1 = std::count(v.begin(), v.end(), target1); int num_items2 = std::count(v.begin(), v.end(), target2); std::cout << "number: " << target1 << " count: " << num_items1 << '\n' ; std::cout << "number: " << target2 << " count: " << num_items2 << '\n' ; } |
Output:
1 2 | number: 3 count: 2 number: 5 count: 0 |
This example uses a lambda expression to count elements divisible by 3.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <algorithm> #include <iostream> #include <vector> int main() { int data[] = { 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 }; std::vector< int > v(data, data+10); int num_items1 = std::count_if(v.begin(), v.end(), []( int i) { return i % 3 == 0;}); std::cout << "number divisible by three: " << num_items1 << '\n' ; } |
Output:
1 | number divisible by three: 3 |
See also
std::experimental::parallel::count
(parallelism TS) | parallelized version of std::count (function template) |
std::experimental::parallel::count_if
(parallelism TS) | parallelized version of std::count_if (function template) |
Please login to continue.