Chapter 5 C++11
C++ 11 is a standard of C++ newly established in 2011, it introduces new functionalities and notations. Compared with the previous standard, many new features have been added to make C++ even easier for beginners. This document will actively exploit these features of C++11.
Important: The code examples in this document are written with C++11 enabled.
5.1 Enabling C++11
To enable C++11, add the following description somewhere in your Rcpp code, this is sufficient when you compile your rcpp code with Rcpp::sourceCpp().
If you want to enable C++11 in your package, add code below in the DESCRIPTION file of your package.
SystemRequirements: C++11
5.2 Recommended C++11 features
5.2.1 Initializer list
Initialization of variables using {}.
// Initialize Vector
// The next three are the same as c (1, 2, 3).
NumericVector v1 = NumericVector::create(1.0, 2.0, 3.0);
NumericVector v2 = {1.0, 2.0, 3.0};
NumericVector v3 {1.0, 2.0, 3.0}; // You can omit "=".
5.2.2 auto
By using the auto specifier, the type of a defined variable is inferred by the compiler automatically according to the assigned value.
// variable "i" will be int
auto i = 4;
NumericVector v;
// variable "it" will be NumericVector::iterator
auto it = v.begin();
5.2.3 decltype
By using decltype, you can declare a variable of the same type as an existing variable.
int i;
decltype(i) x; // variable "x" will be int
5.2.4 Range-based for-loop
You can write a for statement with the same style as R.
IntegerVector v {1,2,3};
int sum=0;
for(auto& x : v) {
sum += x;
}
5.2.5 Lambda expression
You can create a function object by using a lambda expression. A function object is usually created as an unnamed function and passed to the other function.
Lambda expressions are written in the form [](){}.
In [], you write a list of local variables you want to use in this function object.
[]do not allow access to all the local variables from the function object.[=]will copy values of the all local variables to the function object.[&]enables direct access to all local variables from the function object.[=x, &y]means that the local variable “x” will be copied to the function object, and the local variable “y” is allowed to be accessed directly from the function object.
In (), you write arguments to be passed to this function object.
In {}, you describe processes you want.
Return type of the lambda expression
The return type of this function object is automatically set to the type of the returned value described in {}. If you want to define return type explicitly, write it like []()->int{}.
Example
The following example shows how to use a lambda expression. You can find Some types of C++ code can be written in the same style as R.
R example
Rcpp example