Customizing the behavior of std::ranges::count_if()
for specific data types involves writing specialized predicate functions.
These predicates can leverage the properties and methods of the data types to determine the count criteria.
Let's consider a custom class Player
and use std::ranges::count_if()
to count players with specific attributes.
#include <algorithm>
#include <iostream>
#include <vector>
class Player {/*...*/};
int main() {
std::vector<Player> players {
{"Roderick", 100, 10},
{"Anna", 50, 5},
{"Robert", 150, 12}
};
int threshold = 8;
auto highLevelPredicate = [&](const Player& p) {
return p.isHighLevel(threshold);
};
int highLevelCount = std::ranges::count_if(
players, highLevelPredicate);
std::cout << "Number of high-level players: "
<< highLevelCount;
}
Number of high-level players: 2
In this example:
Player
class has an isHighLevel()
method to check if a player's level exceeds a given threshold.main()
, we create a lambda highLevelPredicate
that binds the threshold and uses isHighLevel()
.std::ranges::count_if()
to count players above the threshold level.By writing custom predicates, you can tailor std::ranges::count_if()
to fit various complex criteria, making your code more expressive and powerful.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the 5 main counting algorithms in the C++ standard library: count()
, count_if()
, any_of()
, none_of()
, and all_of()