Kevin Ushey — written Jan 30, 2013 — source
Boost provides a macro, BOOST_FOREACH
, that allows us to easily iterate
over elements in a container, similar to what we might
do in R with sapply
.
In particular, it frees us from having to deal with iterators as we do with
std::for_each
and std::transform
. The macro is also compatible with the
objects exposed by Rcpp.
Side note: C++11 has introduced a similar for-each looping construct of the form
for (T &elem : X) { /*do stuff*/ }
However, CRAN does not (at the time this post was initially written) allow C++11 in uploads and hence this Boost solution might be preferred if you want to use a for-each construct in a package.
The BOOST_FOREACH
macro is exposed when we use #include <boost/foreach.hpp>
.
Make sure the Boost libraries are in your includepath so that they can be found and
included easily. Because it’s a header-only library we don’t have to worry
about external dependencies or linking.
We’ll use a simple example where we square each element in a vector.
[1] 1 4 9 16 25 36 49 64 81 100
[,1] [,2] [,3] [,4] [1,] 1 25 81 169 [2,] 4 36 100 196 [3,] 9 49 121 225 [4,] 16 64 144 256
[1] 1 4 NA 16 NaN Inf Inf
And a quick benchmark:
Unit: microseconds expr min lq median uq max neval square(x) 70.0 70.78 71 72.0 1498 100 x^2 151.5 152.11 153 561.9 2022 100
[1] TRUE
If you are defining your own classes / containers and want them to be compatible with one of these for-each constructs, you will need to define some methods for iteration across these objects. See this post on SO for more details.
For more information on BOOST_FOREACH
, check the documentation
here.