Session Ready
Exercise

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.

Instructions
100 XP
  • 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.