std::count
- C++ course
- Intermediate
- Lesson 72/116
- 5 min
Learn counting with std::count and std::count_if.
std::count
std::count counts how many times a value appears in a range. With int n = std::count(v.begin(), v.end(), 2); you find how many 2s there are. The result is an integer.
Its sibling std::count_if counts elements matching a condition. The condition is given as a lambda or functor: std::count_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }). You will study lambda expressions in detail in the next group. For now it is enough to know that std::count counts a specific value. Both live in <algorithm>.
Counting example
To find how many times a name appears in a class list, you use std::count. It works on std::vector<std::string> too: std::count(names.begin(), names.end(), "Ayşe") gives the number of people named Ayşe.
std::count runs linearly: it checks each element once. The result is of type iterator::difference_type, usually long or ptrdiff_t. You can assign it to an int; for small counts this is fine. If the value is not found it returns 0.
Practice Print the count of a value
For v = {1, 2, 2, 3, 2, 4}, use std::count to find how many 2s there are and print it with std::cout.
Starter code
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 2, 3, 2, 4};
// Print the count of 2s with std::count
return 0;
}Sample solution
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 2, 3, 2, 4};
int n = std::count(v.begin(), v.end(), 2);
std::cout << n;
return 0;
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each algorithm to its purpose
| Term | Meaning |
|---|---|
std::count |
Counts a value |
std::count_if |
Counts by condition |
std::find |
Searches a value |
std::sort |
Sorts |
2 Complete the count call
int n = std::____(v.begin(), v.end(), 2);
int n = std::count(v.begin(), v.end(), 2);
Explanation: std::count gives the count of a value.
3 What does std::count(v.begin(), v.end(), 2) return?
std::vector<int> v = {1, 2, 2, 3, 2};
auto n = std::count(v.begin(), v.end(), 2);- The index of the first 2
- The count of 2s Correct answer
- The size of the vector
- The position of the last 2
Explanation: std::count returns the count of 2s (3).