Indexing a vector
Indexing in C++ starts at 0, so it can help to imagine the index as an offset from the start of the vector. x[0]
is at offset 0
and gives the first element of x
.
This exercise is part of the course
Optimizing R Code with Rcpp
Exercise instructions
- Complete the definition of a function,
first_plus_last()
, that gives the sum of the first and last values of aNumericVector
. - Set
n
to be thesize()
ofx
. - Set
first
to be the first element ofx
. - Set
last
to be the last element ofx
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
#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])
*/