整數序列
你在前面幾個練習中所寫的函式,會先進行計算,然後回傳單一數值。你也可以撰寫會回傳向量的函式。
建立向量型別的語法是:指定向量的型別,加上變數名稱,然後在括號中填入向量的元素個數。例如,若要建立一個名為 numbers、包含 10 個元素的數值向量,程式碼如下:
NumericVector numbers(10);
本練習屬於課程
用 Rcpp 最佳化 R 程式碼
練習說明
- 完成函式
seq_cpp()的定義。它接收兩個整數lo和hi,並回傳介於兩者之間的IntegerVector。- 將回傳型別設為
IntegerVector。 - 建立一個大小為
n的整數向量sequence。 - 在
for迴圈內,將sequence的第 i 個元素設為lo加上i。 - 回傳
sequence。
- 將回傳型別設為
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
#include
using namespace Rcpp;
// Set the return type to IntegerVector
// [[Rcpp::export]]
___ seq_cpp(int lo, int hi) {
int n = hi - lo + 1;
// Create a new integer vector, sequence, of size n
___;
for(int i = 0; i < n; i++) {
// Set the ith element of sequence to lo plus i
___;
}
return ___;
}
/*** R
lo <- -2
hi <- 5
seq_cpp(lo, hi)
# Does it give the same answer as R's seq() function?
all.equal(seq_cpp(lo, hi), seq(lo, hi))
*/