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,
Pointers in C/C++ [Full Course]
#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; }