Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BOOST_FOREACH versus for loop

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?

like image 723
codeJack Avatar asked Feb 21 '13 10:02

codeJack


2 Answers

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).

like image 157
juanchopanza Avatar answered Oct 06 '22 11:10

juanchopanza


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.

like image 27
thiton Avatar answered Oct 06 '22 11:10

thiton