std count if
suggest changetemplate <class InputIterator, class UnaryPredicate>
typename iterator_traits<InputIterator>::difference_type
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
Effects
Counts the number of elements in a range for which a specified predicate function is true
Parameters
first => iterator pointing to the beginning of the range last => iterator pointing to the end of the range pred => predicate function(returns true or false)
Return
The number of elements within the specified range for which the predicate function returned true.
Example
The example uses std::ranges::count_if (C++20) and class template argument deduction (C++17).
#include <algorithm>
#include <iostream>
#include <vector>
/*
Define a few functions to use as predicates
*/
//return true if number is odd
bool isOdd(int value) {
return value % 2 != 0;
}
//functor that returns true if number is greater than the value of the constructor parameter provided
class Greater {
int than_;
public:
explicit Greater(int than) : than_(than) {}
bool operator()(int value) const {
return value > than_;
}
};
int main() {
//create a vector
const std::vector myvec{1, 5, 8, 0, 7, 6, 4, 5, 2, 1, 5, 0, 6, 9, 7};
//using a lambda function to count even numbers
const auto evenCount = std::ranges::count_if(myvec, [](int value) {
return value % 2 == 0;
});
//using function pointer to count odd number in the first half of the vector
const auto oddCount = std::ranges::count_if(
myvec.begin(), myvec.end() - myvec.size() / 2, isOdd);
//using a functor to count numbers greater than 5
const auto greaterCount = std::ranges::count_if(myvec, Greater{5});
std::cout << "vector size: " << myvec.size() << '\n';
std::cout << "even numbers: " << evenCount << " found\n";
std::cout << "odd numbers: " << oddCount << " found\n";
std::cout << "numbers > 5: " << greaterCount << " found\n";
}
vector size: 15
even numbers: 7 found
odd numbers: 4 found
numbers > 5: 6 found
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents