Dirk Eddelbuettel — written Jan 10, 2013 — source
Yesterday’s post started to explore the nice additions which the new C++11 standard is bringing to the language. One particularly interesting feature are lambda functions which resemble the anonymous functions R programmers have enjoyed all along. This shows a simple example.
First, we again make sure the compiler knows that we want C++11. We can either set the flag directly:
or rely on Rcpp (version 0.10.3 or newer) to do it for us via the plugin.
We will revisit an earlier example on stl::transform
but use a lamba function
In this example, the function being swept over all elements of x
does not
have to be declared as a separate function as we did here
but can be defined inline as we would in R. The return type is
deduced automatically, similar to the use auto auto
in the previous C++11
example. We can run the example:
[1] 1 4 9 16
Unsurprisingly, the result is the same. We can also retake the second example from the previous post:
It also matches the previous result.
[1] 2.236 2.828 4.243 5.000
Once again, we need to remind the reader that this still requires setting the
-std=c++11
option for g++
, and that CRAN will not allow this in uploads,
at least not yet. In the meantime, C++11 can of course be used for non-CRAN
projects.