Ashwin Nanjappa
Ashwin Nanjappa

Reputation: 78498

C++ Boost: Any gotchas with BOOST_FOREACH?

This one is for Boost experts. Are there any gotchas or details that the programmer needs to be aware of before he goes in and replaces all his old C/C++ style loops with the lean-and-mean-looking BOOST_FOREACH?

(This question is partly derived from here.)

Upvotes: 22

Views: 8412

Answers (5)

rlbond
rlbond

Reputation: 67749

I profiled BOOST_FOREACH versus a hand-coded loop. BOOST_FOREACH was about 30% slower in a simple loop that incremented the elements of a vector of size 100,000. So, if you are coding a small loop, it is not going to be as fast. Once your loop does major processing, Amdahl's Law kicks in and the loss due to BOOST_FOREACH is negligible.

Upvotes: 7

bayda
bayda

Reputation: 13581

BOOST_FOREACH - macro, I don't like macroses and prefer to use STL algorithms + lambda + bind.

Also C++0x will contain for-loop similar on BOOST_FOREACH:

int my_array[5] = {1, 2, 3, 4, 5};
for(int &x : my_array)
{
  x *= 2;
}

it is one additional reason for don't use partialy dead BOOST_FOREACH.

Upvotes: 9

tstenner
tstenner

Reputation: 10291

As it's just a macro, you can't use commas in typenames, so
BOOST_FOREACH(pair<int,int> A, mapB){}
won't work.
For other disadvantages I'd consult the BOOST_FOREACH() documentation.

Upvotes: 8

dirkgently
dirkgently

Reputation: 111130

Take a look at:

Upvotes: 10

anon
anon

Reputation:

Take a look at the source of the BOOST_FOREACH macro (in foreach.hpp) - it's not what I would call "lean and mean" :-)

Upvotes: 4

Related Questions