Like this article? We recommend
Wrapping it All Up
To wrap this up, here's a quick example that shows you how to use a map in for_each with the help of the lambda library because the preceding example just shows a vector. I'm giving the whole program here, including all the preceding code, too, so you can paste it all into your compiler. The lambda demo is the demoMapLambda function. Also, this code shows you what header files you need from the Boost library to make it all work.
#include <iostream> #include <map> #include <vector> #include <boost/format.hpp> #include "boost/lambda/lambda.hpp" #include "boost/lambda/bind.hpp" #include "boost/lambda/algorithm.hpp" #include "boost/lambda/if.hpp" using namespace std; using boost::format; using namespace boost::lambda; // needed for _1 typedef map<string, string> PhoneList; typedef PhoneList::value_type PhonePair; void eachphone(const PhonePair &item) { cout << item.first << " : " << item.second << endl; } void demoMapAlgo() { PhoneList phones; phones[string("Jeff")] = string("110-555-1234"); phones[string("Angie")] = string("800-123-4567"); phones[string("Dylan")] = string("123-867-5309"); phones[string("Amy")] = string("888-111-1111"); for_each(phones.begin(), phones.end(), eachphone); } void demoMapWhile() { PhoneList phones; phones[string("Jeff")] = string("110-555-1234"); phones[string("Angie")] = string("800-123-4567"); phones[string("Dylan")] = string("123-867-5309"); phones[string("Amy")] = string("888-111-1111"); PhoneList::iterator iter = phones.begin(); while (iter != phones.end()) { cout << iter->first << " : " << iter->second << endl; iter++; } } void demoVector() { vector<int> myvector; myvector.push_back(1); myvector.push_back(2); myvector.push_back(4); myvector.push_back(8); myvector.push_back(16); for_each(myvector.begin(), myvector.end(), cout << _1 << '\n' ); } void demoMapLambda() { PhoneList phones; phones[string("Jeff")] = string("110-555-1234"); phones[string("Angie")] = string("800-123-4567"); phones[string("Dylan")] = string("123-867-5309"); phones[string("Amy")] = string("888-111-1111"); for_each(phones.begin(), phones.end(), cout << bind(&PhonePair::first, _1) << " : " << bind(&PhonePair::second, _1) << "\n" ); } int main() { cout << "=== Map using Algorithm ===" << endl; demoMapAlgo(); cout << "=== Map using While Loop ===" << endl; demoMapWhile(); cout << "=== Vector w/ Algorithm, lambda ===" << endl; demoVector(); cout << "=== Map w/ Algorithm, lambda ===" << endl; demoMapLambda(); return 0; }