8 Key Standard Library Algorithms

Using std::ranges::for_each() with a Member Function

How do I use std::ranges::for_each() with a member function of a class?

Abstract art representing computer programming

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.

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:

  • 125 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