开始使用免费开始使用

向量索引

C++ 的索引从 0 开始,因此可以将索引想象为从向量起始位置的偏移量x[0] 的偏移量为 0,对应 x 的第一个元素。

本练习是课程的一部分

用 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])
*/
编辑并运行代码