Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does converting vectors between Rcpp and C++ (using Rcpp::as or Rcpp::wrap) create a new vector and copy elements?

Tags:

c++

r

vector

rcpp

In my understanding, converting vectors between Rcpp and C++ creates new vectors as follows. Is my understanding right?

When converting an Rcpp vector to a C++ vector, we use Rcpp::as<T>() (e.g. Rcpp::as<std::string> for Rcpp::CharacterVector). std::vector<std::string> is created, and the original Rcpp elements are copied into the C++ vector as std::string. This means that modifying the newly created C++ vector elements does not affect the original Rcpp vector elements.

When converting a C++ vector to an Rcpp vector, we use Rcpp::wrap(). Rcpp vector with the corresponding type is created, and the C++ elements are copied into the Rcpp vector as Rcpp objects. This means that modifying the newly created Rcpp vector elements does not affect the original C++ vector elements.

like image 380
toshi-san Avatar asked Sep 07 '25 05:09

toshi-san


1 Answers

Correct, the following functions perform conversions:

// conversion from R to C++
Rcpp::as<T>();
// conversion from C++ to R
Rcpp::wrap();

In short, moving data from an Rcpp object into a C++ vector and vice versa causes a copy to be made. This has been explained a bit here:

Declare a variable as a reference in Rcpp

For more on the templating, please see the Rcpp Extending vignette.

Details on cost from an Rcpp::*Vector to std::vector<T> can be found here:

Should I prefer Rcpp::NumericVector over std::vector?

One way to avoid the copy is to re-use memory if possible. This is hinted at here:

Deciding between NumericVector and arma::vec in Rcpp

like image 87
coatless Avatar answered Sep 08 '25 17:09

coatless