The example below shows creating a list of people, adding to the tail and the head. We then use for_each to print each one using the Print member function. Then all pointers are deleted.
Output
#include <string>
#include <list>
#include <algorithm>
#include <iostream>
#include <functional>
using namespace std;
struct DeleteObject
{
template <typename T>
void operator() (const T* ptr) const { delete ptr; };
};
class Person
{
// private values
string m_sName;
string m_sEmail;
int m_iAge;
public:
// constructor
Person (const string sName,
const string sEmail,
const int iAge) :
m_sName (sName), m_sEmail (sEmail), m_iAge (iAge) {};
// this is a bit wacky but the MS compiler would not compile
// (the for_each) without a return value, however who cares
// what it is?
// print this person
int Print (void)
{
cout << m_sName
<< " - " << m_sEmail
<< ", age " << m_iAge
<< endl;
return 0; // return value gets discarded
};
};
// a list of people pointers
typedef list<Person*> PersonList;
int main (void)
{
PersonList people;
// add items to list
people.push_back (new Person ("Nick", "nick@some-email-address.com", 15));
people.push_back (new Person ("Fred", "fred@nurk.com.au", 100));
people.push_front (new Person ("John", "john@smith.com.au", 35));
// print everyone (calls member function Print in the person class)
for_each (people.begin (), people.end (), mem_fun (&Person::Print));
// delete all objects in list
for_each (people.begin (), people.end (), DeleteObject ());
// now delete them from the list
people.clear ();
return 0;
} // end of main
Output
John - john@smith.com.au, age 35
Nick - nick@some-email-address.com, age 15
Fred - fred@nurk.com.au, age 100