To use std::ranges::for_each()
with a member function of a class, you'll need to use a std::bind()
or a lambda function to bind the member function to an instance of the class. Here's a simple example to illustrate this process:
First, let's define a class Player
with a member function Log()
:
#include <iostream>
#include <vector>
#include <algorithm>
class Player {
public:
Player(int id) : id{id} {}
void Log() const {
std::cout << "Player ID: " << id << "\n";
}
private:
int id;
};
Now, you can create a vector of Player
objects and use std::ranges::for_each()
to call the Log()
member function on each Player
 object:
#include <algorithm>
#include <iostream>
#include <ranges>
#include <vector>
class Player {
public:
Player(int id) : id{id} {}
void Log() const {
std::cout << "Player ID: " << id << "\n";
}
private:
int id;
};
int main() {
std::vector<Player> players{
Player{1}, Player{2}, Player{3}};
std::ranges::for_each(players, [](Player& p) {
p.Log();
});
}
Player ID: 1
Player ID: 2
Player ID: 3
In this example, we use a lambda function to call the Log()
member function on each Player
object. The lambda captures each Player
object by reference and calls the Log()
 method.
Alternatively, you can use std::bind()
if you prefer:
#include <algorithm>
#include <functional>
#include <iostream>
#include <ranges>
#include <vector>
class Player {
public:
Player(int id) : id{id} {}
void Log() const {
std::cout << "Player ID: " << id << "\n";
}
private:
int id;
};
int main() {
std::vector<Player> players{
Player{1}, Player{2}, Player{3}};
std::ranges::for_each(players,
std::bind(&Player::Log, std::placeholders::_1)
);
}
Player ID: 1
Player ID: 2
Player ID: 3
In this second example, std::bind()
is used to bind the Log()
member function to each Player
 object.
Both approaches allow you to effectively use std::ranges::for_each()
with member functions of a class.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to 8 more useful algorithms from the standard library, and how we can use them alongside views, projections, and other techniques
Comprehensive course covering advanced concepts, and how to use them on large-scale projects.
View Course