First steps in using C++11 with Rcpp

January 9, 2013

(This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers)

The recent release of the C++11 standard has brought a lot of attention to the new language features. Rcpp, as a CRAN package, follows CRAN policy in not (yet!!) supporting the standard for its purported non-portable status. Even as of the current g++ version, we still need to explicitly enable C++11 support which we can do here from R prior to compiling:


C++11 has a lot of nice features; the Wikipedia page is pretty thorough in describing them, and the recently-created ISO C++ website has a lot of additional material.

In a first example, we look at the auto keyword which allows the compiler to infer the type based on the assignment.


// [[Rcpp::export]]
int useAuto() {
    auto val = 42;		// val will be of type int
    return val;

Testing it:

[1] 42

Another lovely feature are initialiser lists:


// [[Rcpp::export]]
std::vector<std::string> useInitLists() {
    std::vector<std::string> vec = {"larry", "curly", "moe"};
    return vec;

Testing it:

[1] "larry" "curly" "moe"  

Lastly, we can appreciate the addition loops over ranges:


// [[Rcpp::export]]
int simpleProd(std::vector<int> vec) {
    int prod = 1;
    for (int &x : vec) {       // loop over all values of vec
       prod *= x;              // access each elem., comp. product
    return prod;

This third example we can also look at:

[1] 120

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. Yet. That time will come though. And in the meantime, this 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. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


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)