How can make the following code inside of for_each more readable?
void f(char*);
typedef std::map
On 9/15/06, Alexander Shyrokov
Is it possible to convert boost::bind(&TMap::value_type::second,_1) to a function object or a typedef name?
Though it's not exactly what you're asking for, one nice way would be to use an iterator adapter that returns base_itr->second when dereferenced. I hear that it's simple to make one with Boost.Iterator. You'd then just do std::for_each( seconder(a.begin()), seconder(a.end()), boost::bind(f,_1) );
Alexander Shyrokov wrote:
How can make the following code inside of for_each more readable?
void f(char*); typedef std::map
TMap; TMap a; std::for_each(a.begin(),a.end(),boost::bind(f,boost::bind(&TMap::value_type::second,_1)));
I use indentation:
std::for_each( a.begin(), a.end(),
boost::bind( f,
boost::bind( &TMap::value_type::second, _1 )
)
);
or a custom for_each for maps:
template
template
void for_each_pair( It first, It last, F f ) { for( ; first != last; ++first ) { f( first->first, first->second ); } } for_each_pair( a.begin(), a.end(), boost::bind( f, _2 ) ); Could you explain why _2 is used? It looks like f parameter should have two parameters and we are using bind to use only 2nd parameter and ignore the first one? Is it correct?
The second question: why last is not a constant and maybe taken by reference? void for_each_pair( It first, const It& last, F f ) Thanks. -- Regards, Alexander. http://sjcomp.com
On 9/15/06, Alexander Shyrokov
Could you explain why _2 is used? It looks like f parameter should have two parameters and we are using bind to use only 2nd parameter and ignore the first one? Is it correct?
boost::bind( f, _2 ) is generating a binary functor that, when called, calls the unary function f and passes it the second argument to the functor.
The second question: why last is not a constant and maybe taken by reference? void for_each_pair( It first, const It& last, F f )
Iterators are supposed to be cheap to copy and as far as I can tell it's just the usual way to pass the end iterator. There might also be some weird issues with argument deduction in some compilers. ( I seem to recall something about that... ) HTH, Scott
Alexander Shyrokov
Is it possible to convert boost::bind(&TMap::value_type::second,_1) to a function object or a typedef name?
Yes: boost::function< void (TMap::value_type) > proc = boost::bind(f, boost::bind(&TMap::value_type::second, _1)); would do it if the signatures did match (f is taking char*, not char). Also, some boost:: q are redundant (ADL): boost::function< void (TMap::value_type) > proc = bind(f, bind(&TMap::value_type::second, _1)); Regards, Jens
participants (4)
-
Alexander Shyrokov
-
Jens Theisen
-
me22
-
Peter Dimov