Reputation: 2503
I would like to have your advice regarding the usage of BOOST_FOREACH
.
I have read around it is not really recommended in terms of performance being a very heavy header.
Moreover, it forces the use of "break" and "continue" statements since you can't really have an exit condition driven by a boolean and I've always been told that "break" and "continue" should be avoided when possible.
Of course, the advantages are that your are not dealing directly with iterators which ease the task of iterating through a container.
What do you think about it?
Do you think that if used it should be adopted systematically to guarantee homogeneity in a project or its use is recommended only under certain circumstances?
Upvotes: 23
Views: 22437
Reputation: 227418
I would say C++ range based loops supercede it. This is an equivalent of this BOOST_FOREACH example:
std::string hello( "Hello, world!" );
for (auto c : hello)
{
std::cout << c;
}
I never found I needed to use it in ++03.
Note when using the range based loop over containers with expensive to copy elements, or in a generic context, it is best to use const&
to those elements:
SomeContainerType<SomeType> v = ....;
for (const auto& elem : v)
{
std::cout << elem << " ";
}
Similarly, if you need to modify the elements of the container, then use a non-const & (auto& elem : v
).
Upvotes: 28
Reputation: 111
I just replaced a use of BOOST_FOREACH with a simple for loop and got a 50% speedup, so I would say it is definitely not always the best thing to use. You will also not get a loop counter (e.g. "i") which sometimes you actually need. Personally I'm not a fan but YMMV if it suits your style better.
BTW - a "heavy header" won't affect performance of your program, only the compilation time.
Upvotes: 5
Reputation: 36049
In programming, clarity is trump. I've always used boost foreach in C++03, found it much more readable than the hand-written loop, the header size won't kill you. As @juanchopanza rightly noted, of course, this question is obsolete in C++11.
Your concerns with break and continue are unfounded and probably counterproductive. With the traditionally long for-loop headers of C++03, people tend to not read the loop header and to overlook any condition variables that hide in the loop header. Better make your intent explicit with break and continue.
If you have decided to use boost foreach, use it systematically. It is supposed to be used to replace the bread-and-butter loops, after all.
Upvotes: 10