std count
suggest changetemplate <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count (InputIterator first, InputIterator last, const T& val);
Effects
Counts the number of elements that are equal to val
Parameters
first => iterator pointing to the beginning of the range
last => iterator pointing to the end of the range
val => The occurrence of this value in the range will be counted
Return
The number of elements in the range that are equal(==) to val.
Example
The example uses std::ranges::count and std::ranges::find (C++20) and class template argument deduction (C++17).
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
//create vector
const std::vector intVec{4, 6, 8, 9, 10, 30, 55, 100, 45, 2, 4, 7, 9, 43, 48};
//count occurrences of 9, 55, and 101
const auto count_9 = std::ranges::count(intVec, 9); // occurs twice
const auto count_55 = std::ranges::count(intVec, 55); // occurs once
const auto count_101 = std::ranges::count(intVec, 101); // does not occur
//print result
std::cout << "There are " << count_9 << " 9s\n";
std::cout << "There is " << count_55 << " 55\n";
std::cout << "There is " << count_101 << " 101\n";
//find the first element == 4 in the vector
const auto itr_4 = std::ranges::find(intVec, 4);
//count its occurrences in the vector starting from the first one
const auto count_4 = std::ranges::count(itr_4, intVec.end(), *itr_4);
std::cout << "There are " << count_4 << ' ' << *itr_4 << '\n';
}
There are 2 9s
There is 1 55
There is 0 101
There are 2 4
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents