简体   繁体   English

在 Rcpp 和 C++(使用 Rcpp::as 或 Rcpp::wrap)之间转换向量是否会创建新向量并复制元素?

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

In my understanding, converting vectors between Rcpp and C++ creates new vectors as follows.据我了解,在 Rcpp 和 C++ 之间转换向量会创建如下新向量。 Is my understanding right?我的理解对吗?

When converting an Rcpp vector to a C++ vector, we use Rcpp::as<T>() (eg Rcpp::as<std::string> for Rcpp::CharacterVector ).将 Rcpp 向量转换为 C++ 向量时,我们使用Rcpp::as<T>() (例如Rcpp::as<std::string>用于Rcpp::CharacterVector )。 std::vector<std::string> is created, and the original Rcpp elements are copied into the C++ vector as std::string .创建std::vector<std::string> ,并将原始 Rcpp 元素作为std::string复制到 C++ 向量中。 This means that modifying the newly created C++ vector elements does not affect the original Rcpp vector elements.这意味着修改新创建的 C++ 向量元素不会影响原始 Rcpp 向量元素。

When converting a C++ vector to an Rcpp vector, we use Rcpp::wrap() .将 C++ 向量转换为 Rcpp 向量时,我们使用Rcpp::wrap() Rcpp vector with the corresponding type is created, and the C++ elements are copied into the Rcpp vector as Rcpp objects.创建相应类型的 Rcpp 向量,并将 C++ 元素作为 Rcpp 对象复制到 Rcpp 向量中。 This means that modifying the newly created Rcpp vector elements does not affect the original C++ vector elements.这意味着修改新创建的 Rcpp 向量元素不会影响原始的 C++ 向量元素。

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.简而言之,将数据从 Rcpp object 移动到 C++ 向量(反之亦然)会导致复制。 This has been explained a bit here:此处已对此进行了一些解释:

Declare a variable as a reference in Rcpp 在 Rcpp 中声明一个变量作为引用

For more on the templating, please see the Rcpp Extending vignette.有关模板的更多信息,请参阅Rcpp 扩展小插图。

Details on cost from an Rcpp::*Vector to std::vector<T> can be found here:Rcpp::*Vectorstd::vector<T>的成本详情可以在这里找到:

Should I prefer Rcpp::NumericVector over std::vector? 我应该更喜欢 Rcpp::NumericVector 而不是 std::vector?

One way to avoid the copy is to re-use memory if possible.避免复制的一种方法是尽可能重复使用 memory。 This is hinted at here:这里暗示了这一点:

Deciding between NumericVector and arma::vec in Rcpp 在 Rcpp 中选择 NumericVector 和 arma::vec

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM