Iterating over a range of User Defined objects and calling member function using std::for_each

In this article we will see how we can iterate over a range of user defined objects and and call a member function on each of the iterating element.

Let’s see an example.

Suppose we have a vector of Student class objects and we want to call a member function on each of the element in vector. We will do this by using std::for_each

Example Program :

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

// Student class created
class Student
{
    int m_id;
    std::string m_name;
public:
    Student(int id, std::string name)
    {
        m_id = id;
        m_name = name;
    }
    void displayStudentInfo()
    {
        std::cout<<"Student ID :: "<<m_id<< "  , Name :: "<<m_name<<std::endl;
    }
};

// A std::vector of Student Pointers created and initialized 
void getStudentList(std::vector<Student *> & vecOfStudent)
{
    vecOfStudent.push_back(new Student(1, "Akash"));
    vecOfStudent.push_back(new Student(1, "Prakash"));
    vecOfStudent.push_back(new Student(1, "Abhisek"));
    vecOfStudent.push_back(new Student(1, "Arshlaan"));
}

// In this iterating all the elements in vector and calling displayStudentInfo member function for each of the element
int main()
{
    std::vector<Student *> vecOfStudent;
    getStudentList(vecOfStudent);
    std::for_each(vecOfStudent.begin(), vecOfStudent.end(), std::bind(std::mem_fun(&Student ::displayStudentInfo),std::placeholders::_1) );
    std::for_each(vecOfStudent.begin(), vecOfStudent.end(), [](Student * stu)
    {
        delete stu;
    } );
    return 0;
}
Output :

Student ID :: 1 , Name :: Akash
Student ID :: 1 , Name :: Prakash
Student ID :: 1 , Name :: Abhisek
Student ID :: 1 , Name :: Arshlaan