向量索引
C++ 的索引从 0 开始,因此可以将索引想象为从向量起始位置的偏移量。x[0] 的偏移量为 0,对应 x 的第一个元素。
本练习是课程的一部分
用 Rcpp 优化 R 代码
练习说明
- 完成函数
first_plus_last()的定义,该函数返回NumericVector的首尾元素之和。 - 将
n设为x的size()。 - 将
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])
*/