開始使用免費開始

向量的索引

在 C++ 中,索引從 0 開始,所以把「索引視為從向量起點的位移量」會很有幫助。x[0] 的位移量是 0,會取得 x 的第 1 個元素。

本練習屬於課程

用 Rcpp 最佳化 R 程式碼

檢視課程

練習說明

  • 完成函式 first_plus_last() 的定義,讓它回傳 NumericVector 的第一個值與最後一個值的總和。
  • n 設為 xsize()
  • first 設為 x 的第一個元素。
  • last 設為 x 的最後一個元素。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

#include 
using namespace Rcpp;

// [[Rcpp::export]]
double first_plus_last(NumericVector x) {
    // The size of x
    int n = ___;
    // The first element of x
    double first = ___;
    // The last element of x
    double last = ___;
    return first + last;
}

/*** R
x <- c(6, 28, 496, 8128)
first_plus_last(x)
# Does the function give the same answer as R?
all.equal(first_plus_last(x), x[1] + x[4])
*/
編輯並執行程式碼