title: How to extract multiple values from a NumericVector in C++
body: <p>I'm quite a newbie to <code>Rcpp</code> and its functionalities, not to mention C++ per se, so this might probably seem trivial to the experts among you. However, there's no such thing as a stupid question, so anyway:  </p>
  
  <p>I was wondering if there was a method to address multiple elements of a NumericVector in C++ at once using indexing. To make the whole thing more clear, here's the R equivalent of what I'm trying to do:</p>
  
  <pre><code># Initial vector
  x &lt;- 1:10
  
  # Extract the 2nd, 5th and 8th element of the vector
  x[c(2, 5, 8)]
  [1] 2 5 8
  </code></pre>
  
  <p>This is what I got so far in the C++ function that I'm executing in R using <code>sourceCpp</code>. It works, but it seems quite inconvenient to me. Is there any easier way to achieve my goals?</p>
  
  <pre><code>#include &lt;Rcpp.h&gt;
  using namespace Rcpp;
  
  // [[Rcpp::export]]
  NumericVector subsetNumVec(NumericVector x, IntegerVector index) {  
    // Length of the index vector
    int n = index.size();
    // Initialize output vector
    NumericVector out(n);
  
    // Subtract 1 from index as C++ starts to count at 0
    index = index - 1; 
    // Loop through index vector and extract values of x at the given positions
    for (int i = 0; i &lt; n; i++) {
      out[i] = x[index[i]];
    }
  
    // Return output
    return out;
  }
  
  /*** R
    subsetNumVec(1:10, c(2, 5, 8))
  */
  &gt;   subsetNumVec(1:10, c(2, 5, 8))
  [1] 2 5 8
  </code></pre>