I find boost::foreach very useful as it saves me a lot of writing. For example, let's say I want to print all the elements in a list:
std::list<int> numbers = { 1, 2, 3, 4 };
for (std::list<int>::iterator i = numbers.begin(); i != numbers.end(); ++i)
cout << *i << " ";
boost::foreach makes the code above much simplier:
std::list<int> numbers = { 1, 2, 3, 4 };
BOOST_FOREACH (int i, numbers)
cout << i << " ";
Much better! However I never figured out a way (if it's at all possible) to use it for std::map
s. The documentation only has examples with types such as vector
or string
.