Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much of STL is too much? [closed]

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?

like image 936
Darius Kucinskas Avatar asked Apr 09 '09 13:04

Darius Kucinskas


1 Answers

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
}
like image 176
Brian R. Bondy Avatar answered Nov 11 '22 18:11

Brian R. Bondy