A first lambda function with C++11 and Rcpp

[This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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:

Sys.setenv("PKG_CXXFLAGS"="-std=c++11")

We will revisit an earlier example on stl::transform but use a lamba function

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
std::vector<double> transformEx(const std::vector<double>& x) {
    std::vector<double> y(x.size());
    std::transform(x.begin(), x.end(), y.begin(), 
                   [](double x) { return x*x; } );
    return y;
}

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:

x <- c(1,2,3,4)
transformEx(x)


[1]  1  4  9 16

Unsurprisingly, the result is the same. We can also retake the second example from the previous post:

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector transformEx2(NumericVector x, NumericVector y) {
    NumericVector z(x.size());
    std::transform(x.begin(), x.end(), y.begin(), z.begin(), 
                   [](double x, double y) { return sqrt(x*x + y*y); } );
    return z;
}

It also matches the previous result.

x <- c(1,2,3,4)
y <- c(2,2,3,3)
transformEx2(x,y)


[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.

To leave a comment for the author, please follow the link and comment on their blog: Rcpp Gallery.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)