Is there any reason why I should prefer Rcpp::NumericVector over std::vector?
For example, the two functions below
Are equivalent when considering their working and benchmarked performance.
SEXP to std::vector requires a deep copy from one data structure to another. (And as I was typing this, @DirkEddelbuettel ran a microbenchmark.)const Rcpp::NumericVector& x) is just visual sugar. By default, the object given is a pointer and as such can easily have a ripple modification effect (see below). Thus, there is no true match that exists with const std::vector& x that effectively "locks" and "passes a references".Can using
std::vectorlead to any possible problems when interacting with R?
In short, no. The only penalty that is paid is the transference between objects.
The gain over this transference is the fact that modifying a value of a NumericVector that is assigned to another NumericVector will not cause a domino update. In essence, each std::vector is a direct copy of the other. Therefore, the following couldn't happen:
#include
// [[Rcpp::export]]
void test_copy(){
NumericVector A = NumericVector::create(1, 2, 3);
NumericVector B = A;
Rcout << "Before: " << std::endl << "A: " << A << std::endl << "B: " << B << std::endl;
A[1] = 5; // 2 -> 5
Rcout << "After: " << std::endl << "A: " << A << std::endl << "B: " << B << std::endl;
}
Gives:
test_copy()
# Before:
# A: 1 2 3
# B: 1 2 3
# After:
# A: 1 5 3
# B: 1 5 3
Is there any reason why I should prefer
Rcpp::NumericVectoroverstd::vector?
There are a few reasons:
Rcpp::NumericVector avoids a deep copy to and fro the C++ std::vector..attr())