|
Boost : |
Subject: [boost] Wrapper around STL algorithms
From: Shevchenko Denis (for.dshevchenko_at_[hidden])
Date: 2010-12-24 16:38:20
Hi friends!
Between work on my Configurator (beta version on the way) I remembered
an old idea to simplify work with STL algorithms. This is not a library,
but just a simple wrapperaround algorithms from <algorithm> header. Main
purpose of this - deliverance from direct work with iterators.
Iterators is the perfect tool, but it is often a source of stupidmistakes:
typedef std::vector< int > V;
typedef V::iterator Vit;
V v1 = list_of( 1 )( 2 )( 3 );
Vitit1 = std::find( v1.begin(), v1.begin(), 2 ); // Oops, we use same
iterator...
V v2 = list_of( 34 )( 56 )( 78 );
Vitit2 = std::find( v2.begin(), v1.end(), 56 ); // Oops, we use
iterators from different containers...
The most offensive is that such mistakes are not detected at
compile-time (at least in GCC), because, strictly speaking,it is not
language error, but logical error.Sometimes I make such mistakes in my
code...
Possible solution:
template
<
typename Container
, typename Value
>
inline typename Container::const_iterator
simple_find( const Container& cont, const Value& value ) {
return std::find( cont.begin(), cont.end(), value );
}
or like this:
template
<
typename Container
, typename Value
>
inline typename boost::range_iterator< const Container >::type
simple_find( const Container& cont, const Value& value ) {
return std::find( boost::begin( cont ), boost::end( cont ), value );
}
In this case we can write:
V v1 = list_of( 1 )( 2 )( 3 );
Vitit1 = simple_find( v1, 2 );
V v2 = list_of( 34 )( 56 )( 78 );
Vitit2 = simple_find( v2, 56 );
Similarly possible to wrap all of the standard algorithms, that will
simplify code and improve its reliability.
Additionally it is possible to simplify the writing of standard idioms,
for example:
template
<
typename Container
, typename Value
>
inline void simple_erase_all( Container& cont, const Value& value ) {
cont.erase( std::remove( boost::begin( cont ), boost::end( cont ), value ),
boost::end( cont ) );
}
Example of code:
V v3 = list_of( 111 )( 333)( 333 );
simple_erase_all( v3, 333 );
I think that this wrapper could be a part ofBoost.Utility.
What do you think about it?
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk