Chapter 52. Boost.Foreach

    Example 52.1. Using BOOST_FOREACH and BOOST_REVERSE_FOREACH

    Anything offering iterators, such as containers from the standard library, classifies as a sequence. Boost.Foreach uses Boost.Range instead of directly accessing the member functions begin() and end(). However, because Boost.Range is based on iterators, anything providing iterators is compatible with BOOST_FOREACH.

    The second loop uses the macro BOOST_REVERSE_FOREACH, which works the same as BOOST_FOREACH, but iterates backwards over a sequence. The loop writes the numbers 9, 4, 1, and 0 in that order to the standard output stream.

    Please note that you should not use operations that invalidate the iterator inside the loop. For example, elements should not be added or removed while iterating over a vector. BOOST_FOREACH and BOOST_REVERSE_FOREACH require iterators to be valid throughout the whole iteration.