开始使用免费开始使用

向量克隆

与 R 不同,C++ 使用的是按引用复制机制。这意味着,如果您复制了一个变量并对副本进行修改,原始变量也会发生相应的变化。

// [[Rcpp::export]]
NumericVector always_returns_two(NumericVector x) {
  // Make a copy
  NumericVector y = x;
  // Modify the copy
  y[0] = 2;
  // The changes also happen in the original
  return x[0];
}

要避免这种行为,您需要使用 clone() 函数,将原始变量的底层数据复制到新变量中。语法为 y = clone(x)。 在本练习中,我们为您定义了两个函数:

  • change_negatives_to_zero():接收一个数值向量,将其中的负数替换为 0,然后返回原始向量和副本。
  • change_negatives_to_zero_with_cloning():完成与上面相同的工作,但在修改前先克隆原始向量。

本练习是课程的一部分

用 Rcpp 优化 R 代码

查看课程

练习说明

  • 完成 change_negatives_to_zero() 的函数定义,将 the_original 赋给 the_copy
  • 完成 change_negatives_to_zero_with_cloning() 的函数定义,将 the_copy 设为 the_original 的克隆。
  • 阅读控制台输出,对比两个函数的结果。

交互式实操练习

通过完成这段示例代码来试试这个练习。

#include 
using namespace Rcpp;

// [[Rcpp::export]]
List change_negatives_to_zero(NumericVector the_original) {
  // Set the copy to the original
  NumericVector the_copy = ___;
  int n = the_original.size();
  for(int i = 0; i < n; i++) {
    if(the_copy[i] < 0) the_copy[i] = 0;
  }
  return List::create(_["the_original"] = the_original, _["the_copy"] = the_copy);
}

// [[Rcpp::export]]
List change_negatives_to_zero_with_cloning(NumericVector the_original) {
  // Clone the original to make the copy
  NumericVector the_copy = ___;
  int n = the_original.size();
  for(int i = 0; i < n; i++) {
    if(the_copy[i] < 0) the_copy[i] = 0;
  }
  return List::create(_["the_original"] = the_original, _["the_copy"] = the_copy);
}

/*** R
x <- c(0, -4, 1, -2, 2, 4, -3, -1, 3)
change_negatives_to_zero(x)
# Need to define x again because it's changed now
x <- c(0, -4, 1, -2, 2, 4, -3, -1, 3)
change_negatives_to_zero_with_cloning(x)
*/
编辑并运行代码