STL vectors
The standard template library (stl) is a C++ library containing flexible algorithms and data structures. For example, the double vector from the stl is like a "native C++" equivalent of Rcpp's NumericVector
. the following code creates a standard double vector named x
with ten elements.
std::vector<double> x(10);
Usually it makes more sense to stick with Rcpp vector types because it gives you access to many convenience methods that work like their R equivalents, including mean()
, round()
, and abs()
. However, the stl vectors have an advantage that they can dynamically change size without paying for data copy every time. That allows us to write simpler code, like the "bad" function from the previous exercise, while retaining the performance of the "good" code.
This exercise is part of the course
Optimizing R Code with Rcpp
Exercise instructions
- Complete the definition of
select_positive_values_std()
, an stl vector-based function to select positive numbers.- Set the return type of the function to a standard double vector using
std::vector<double>
. - Define a standard double vector,
positive_x
, with size0
. - Inside the
if
block in thefor
loop, use thepush_back()
ofpositive_x
to append the ith element ofx
.
- Set the return type of the function to a standard double vector using
good_select_positive_values_cpp()
from the previous exercise is available in your workspace for comparison. Examine the console output to see the relative speeds of the two functions.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
#include
using namespace Rcpp;
// Set the return type to a standard double vector
// [[Rcpp::export]]
___ select_positive_values_std(NumericVector x) {
int n = x.size();
// Create positive_x, a standard double vector
___;
for(int i = 0; i < n; i++) {
if(x[i] > 0) {
// Append the ith element of x to positive_x
___;
}
}
return positive_x;
}
/*** R
set.seed(42)
x <- rnorm(1e6)
# Does it give the same answer as R?
all.equal(select_positive_values_std(x), x[x > 0])
# Which is faster?
microbenchmark(
good_cpp = good_select_positive_values_cpp(x),
std = select_positive_values_std(x)
)
*/