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

In this article we will discuss how to iterate over a container of user defined objects and call a member function on each of the iterating element.
Suppose you have a vector of Employee class objects and you want to call a member function on each of the element in vector.

[showads ad=inside_post]

Let’s see how to do this using std::for_each,

First Create an Employee Class,

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <memory>
class Employee
{
    int m_id;
    std::string m_name;
public:
    Employee(int id, std::string name)
    {
        m_id = id;
        m_name = name;
    }
    void displayEmployeeInfo()
    {
        std::cout<<"Employee ID :: "<<m_id<< "  , Name :: "<<m_name<<std::endl;
    }
};

Then Create a std::vector of Employee Pointers and initialize that,

void getEmployeeList(std::vector<Employee *> & vecOfEmployees)
{
    vecOfEmployees.push_back(new Employee(1, "Varun"));
    vecOfEmployees.push_back(new Employee(1, "John"));
    vecOfEmployees.push_back(new Employee(1, "Ritu"));
    vecOfEmployees.push_back(new Employee(1, "Jack"));
}

Now Iterate through all the elements in vector and call displayEmployeeInfo member function for each of the element,
Also, In the end delete all the elements using std::for_each again.

int main()
{
    std::vector<Employee *> vecOfEmployees;
    getEmployeeList(vecOfEmployees);
    std::for_each(vecOfEmployees.begin(), vecOfEmployees.end(), std::bind(std::mem_fun(&Employee::displayEmployeeInfo),std::placeholders::_1) );
    std::for_each(vecOfEmployees.begin(), vecOfEmployees.end(), [](Employee * emp){
                                                                                delete emp;
                                                                            } );
    return 0;
}

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top