Boost logo

Boost :

From: Maxim Egorushkin (e-maxim_at_[hidden])
Date: 2003-10-05 09:07:08


Eric wrote:

ES> Could someone give me an example of how one would iterate through a
ES> map, printing out the key and values for each element, using the lambda
ES> library?

Here it is:

#include <iostream>
#include <algorithm>
#include <map>
#include <string>

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>

using namespace std;
namespace lm = boost::lambda;

typedef map<string, int> the_map;

void f()
{
the_map m;
m["Natasha"] = 1;
m["Maxim"] = 2;
for_each(m.begin(), m.end(),
(
cout << lm::constant("key: ") << lm::bind(&the_map::value_type::first, lm::_1),
cout << lm::constant("\tvalue: ")<< lm::bind(&the_map::value_type::second, lm::_1) << '\n'
)
);
}

int main()
{
f();
return 0;
}

But I wonder, would it be more simple to define

ostream& operator<<(ostream&, const the_map::value_type&);

and print a map using

copy(m.begin(), m.end(), ostream_iterator<the_map::value_type>(cout, "\n"));

?


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk