Copyright ? 2004 Eric Niebler Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) Table of Contents
What
is
|
Note | |
---|---|
The support for STL containers is very general; anything that looks like
an STL container counts. If it has nested |
See the section on Extensibility
to find out how to make BOOST_FOREACH
work with other types.
Below are some examples that demonstrate all the different ways we can use
BOOST_FOREACH
.
Iterate over an STL container:
std::list<int> list_int( /*...*/ ); BOOST_FOREACH( int i, list_int ) { // do something with i }
Iterate over an array, with covariance (i.e., the type of the iteration variable is not exactly the same as the element type of the container):
short array_short[] = {1,2,3}; BOOST_FOREACH( int i, array_short ) { // The short was implicitly converted to an int }
Predeclare the loop variable, and use break
,
continue
, and return
in the loop body:
std::deque<int> deque_int( /*...*/ ); int i = 0; BOOST_FOREACH( i, deque_int ) { if( i == 0 ) return; if( i == 1 ) continue; if( i == 2 ) break; }
Iterate over a sequence by reference, and modify the underlying sequence:
short array_short[] = { 1, 2, 3 }; BOOST_FOREACH( short & i, array_short ) { ++i; } // array_short contains {2,3,4} here
Iterate over a vector of vectors with nested BOOST_FOREACH
loops. In this example, notice that braces around the loop body are not necessary:
std::vector<std::vector<int> > matrix_int; BOOST_FOREACH( std::vector<int> & row, matrix_int ) BOOST_FOREACH( int & i, row ) ++i;
Iterate over an expression that returns a sequence by value (i.e. an rvalue):
extern std::vector<float> get_vector_float(); BOOST_FOREACH( float f, get_vector_float() ) { // Note: get_vector_float() will be called exactly once }
Iterate in reverse:
std::list<int> list_int( /*...*/ ); BOOST_REVERSE_FOREACH( int i, list_int ) { // do something with i }
Iterating over rvalues doesn't work on some older compilers. Check the Portability section to see whether your compiler supports this.
BOOST_FOREACH
Prettier
People have complained about the name BOOST_FOREACH
. It's
too long. ALL CAPS
can get tiresome to look at. That may be true, but BOOST_FOREACH
is merely following the Boost
Naming Convention. That doesn't mean you're stuck with it, though.
If you would like to use a different identifier (foreach
,
perhaps), you can simply do:
#define foreach BOOST_FOREACH #define reverse_foreach BOOST_REVERSE_FOREACH
Only do this if you are sure that the identifier you choose will not cause name conflicts in your code.
Note | |
---|---|
Do not use |
Last revised: November 02, 2008 at 13:06:18 GMT |