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;
    }
};

Advertisements

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;
}

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

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

Scroll to Top