|
Boost : |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-09-17 06:47:19
From: "Shane Beasley" <sbeasley_at_[hidden]>
>
> I have a std::map<K, Foo> over which I wish to iterate, using STL and
> Boost templates to call a non-const member function on each Foo object.
> The solution would appear to be something like
>
> std::for_each(m.begin(), m.end(), func);
>
> where func(x) would call x.second.mem_fun(). The trouble is defining func
> in terms of STL and Boost components. [...]
>
> (a) In theory, I should be able to use compose_f_gx, [...]
> (b) Use boost::lambda to do something similar to the above.[...]
This is rapidly turning into a FAQ. :-)
compose_f_gx can be emulated by both boost::bind and lambda::bind as bind(f,
bind(g, _1)).
http://www.boost.org/libs/bind/bind.html#nested_binds
Lambda can access a data member as (&_1)->*&std::map<K,
Foo>::value_type::second. Boost.Bind can do the same via the syntax
bind(&std::map<K, Foo>::value_type::second, _1).
The most practical solution, though, is to sidestep the member access issue:
template<class It, class F> void for_each_pair(It first, It last, F f)
{
for(; first != last; ++first)
{
f(first->first, first->second);
}
}
for_each_pair(m.begin(), m.end(), boost::bind(&Foo::mem_fun, _2));
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk