I am using a lot of STL
code with std::for_each
, bind
, and so on, but I noticed that sometimes STL
usage is not good idea.
For example if you have a std::vector
and want to do one action on each item of the vector, your first idea is to use this:
std::for_each(vec.begin(), vec.end(), Foo())
and it is elegant and ok, for a while. But then comes the first set of bug reports and you have to modify code. Now you should add parameter to call Foo()
, so now it becomes:
std::for_each(vec.begin(), vec.end(), std::bind2nd(Foo(), X))
but that is only temporary solution. Now the project is maturing and you understand business logic much better and you want to add new modifications to code. It is at this point that you realize that you should use old good:
for(std::vector::iterator it = vec.begin(); it != vec.end(); ++it)
Is this happening only to me? Do you recognise this kind of pattern in your code? Have you experience similar anti-patterns using STL
?
Using boost::bind with std::for_each solves this problem in a clean way. Or you can use BOOST_FOREACH.
Example of std::for_each:
std::for_each(v.begin(), v.end(), boost::bind(&C::f, _1, param));
Example of BOOST_FOREACH:
std::list<int> list_int( /*...*/ );
BOOST_FOREACH( int i, list_int )
{
// do something with i
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With