What is the usage of the count function in C++?
The count function is used to count the number of times a value appears within a specified range. Here is its syntax:
#include <algorithm>
int count(InputIt first, InputIt last, const T &value);
In this case, InputIt is the type of input iterator, first and last respectively represent the starting and ending positions of the range to be counted, value represents the value whose occurrence is to be counted. The function returns the count of occurrences.
Example Usage:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 1, 2, 1, 4};
int num = std::count(vec.begin(), vec.end(), 1);
std::cout << "Number of occurrences of 1: " << num << std::endl;
return 0;
}
The above code will output:
Number of occurrences of 1: 3