Re: for_each loop on a map without a functor
On Jan 17, 10:49 am, nguillot <nicolas.guil...@gmail.com> wrote:
Hello
I used to loop on a std::map<k, d> to act on the data (d) like that (d
being a class with setIntMember method):
typedef std::map<k, d> tMap;
struct setIntMember
{
setIntMember(int j) : i(j) {}
void operator()(tMap::value_type& pair)
{ pair.second.setIntMember(i); }
int i;
};
The loop being:
for_each(m.begin(), m.end(), setIntMember(4));
I searched for a method to write all in the for_each loop (to avoid
increasing the functors).
We need a function returning the second member of the pair
tMap::value_type,
and their is the SGI template:
template<typename _Pair>
struct Select2nd : public unary_function<_Pair,
typename _Pair::second=
_type>
{
typename _Pair::second_type& operator()(_Pair& __x) const
{ return __x.second; }
const typename _Pair::second_type& operator()(const _Pair&=
__x) const
{ return __x.second; }
};
But I didn't manage to write a single line to perform the for_each
loop, thanks to Select2nd with for_each, bind2nd and mem_fun and
mem_fun1
I didn't manage with boost::bind (on VC++ 6.0):
With boost, I can access the objects like that:
for_each(m.begin(), m.end(),
boost::bind(&d::Trace, boost::bind(&tMap::value_type::seco=
nd,
_1)));
but the d::Trace method is called on a temporary object, so I cannot
modify the content of the objects contained in the map.
Some ideas?
Just use the functor you created. It's simple and clean... You might
want to generalized it a little bit:
template < typename Pair, typename Op >
class CallFuncOn2nd_t {
Op fn;
public:
CallFuncOn2nd_t( Op fn ): fn(fn) { }
typename Op::result_type operator()( Pair& v ) const {
return fn( v.second );
}
};
template < typename Pair, typename Op >
CallFuncOn2nd_t<Pair, Op> callFuncOn2nd( Op fn ) {
return CallFuncOn2nd_t<Pair, Op>( fn );
}
for_each(m.begin(), m.end(),
callFuncOn2nd<tMap::value_type>(bind2nd(mem_fun_ref(&d::setIntMember),
4)));