double 向量的總和
因為在 C++ 中的迴圈通常比 R 快很多,所以撰寫迴圈是一項重要技能。先來寫一個從 NumericVector 加總數值的函式。這會複習你在第 2 章練習 10,以及本章前一個練習中學到的技巧。
本練習屬於課程
用 Rcpp 最佳化 R 程式碼
練習說明
- 完成函式
sum_cpp的定義,讓它遍歷NumericVector的各元素並回傳總和。- 將
n設為x的size()。 - 將
result初始化為 0。 - 指定
for迴圈的引數。將i初始化為0,設定迭代條件為i小於n,每步將i加 1。 - 在每次迭代中,把
x的第 i 個元素加到result。
- 將
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
#include
using namespace Rcpp;
// [[Rcpp::export]]
double sum_cpp(NumericVector x) {
// The size of x
int n = ___;
// Initialize the result
double result = ___;
// Complete the loop specification
for(int i = 0; ___; ___) {
// Add the next value
result = result + ___;
}
return result;
}
/*** R
set.seed(42)
x <- rnorm(1e6)
sum_cpp(x)
# Does the function give the same answer as R's sum() function?
all.equal(sum_cpp(x), sum(x))
*/