Counting Algorithms

Using Member Functions as Predicates with std::ranges::any_of()

How can I use std::ranges::any_of() with a member function that requires parameters?

Abstract art representing computer programming

Using std::ranges::any_of() with a member function that requires parameters involves binding the required parameters to the function. The std::bind utility or lambdas can help with this. Here's an example:

#include <algorithm>
#include <iostream>
#include <vector>
#include <functional>

class Player {/*...*/}; int main() { std::vector<Player> Party { Player{"Roderick", 100}, Player{"Anna", 50}, Player{"Robert", 150} }; int threshold = 100; auto isHealthy = [&](const Player& p) { return p.hasHealthGreaterThan(threshold); }; bool anyHealthy = std::ranges::any_of( Party, isHealthy); std::cout << "Any player with health greater than " << threshold << "? " << (anyHealthy ? "Yes" : "No"); }
Any player with health greater than 100? Yes

In this example:

  • The Player class has a member function hasHealthGreaterThan() that checks if a player's health exceeds a given threshold.
  • In the main() function, we create a lambda isHealthy that binds the threshold variable and calls hasHealthGreaterThan().
  • We then pass this lambda to std::ranges::any_of() to check if any player in the Party vector has health greater than the threshold.

This technique can be adapted to other member functions requiring parameters.

By using lambdas or std::bind, you can effectively use member functions with std::ranges algorithms, enhancing the flexibility and reusability of your code.

This Question is from the Lesson:

Counting Algorithms

An introduction to the 5 main counting algorithms in the C++ standard library: count(), count_if(), any_of(), none_of(), and all_of()

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Counting Algorithms

An introduction to the 5 main counting algorithms in the C++ standard library: count(), count_if(), any_of(), none_of(), and all_of()

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved