ComeçarComece de graça

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.

Este exercício faz parte do curso

Optimizing R Code with Rcpp

Ver curso

Instruções do exercício

  • 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 size 0.
    • Inside the if block in the for loop, use the push_back() of positive_x to append the ith element of x.
  • 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.

Exercício interativo prático

Experimente este exercício completando este código de exemplo.

#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)
)
*/
Editar e executar o código