在C++中,我们可以将变量声明为引用.
int a = 10;
int& b = a;
Run Code Online (Sandbox Code Playgroud)
如果我们设置b=15,a也会改变.
我想在Rcpp做类似的事情.
List X = obj_from_R["X"];
IntegerVector x_i = X[index];
x_i = value;
Run Code Online (Sandbox Code Playgroud)
我想X通过在其向量之一中插入一个值来更新R中的对象.上面的代码不起作用,所以我尝试了这个:
IntegerVector& x_i = X[index];
Run Code Online (Sandbox Code Playgroud)
并收到错误.
error: non-const lvalue reference to type 'IntegerVector'
(aka 'Vector<13>') cannot bind to a temporary of type 'Proxy' (aka 'generic_proxy<19>')
Run Code Online (Sandbox Code Playgroud) 考虑这种比较:
require(Rcpp)
require(microbenchmark)
cppFunction('int cppFun (int x) {return x;}')
RFun = function(x) x
x=as.integer(2)
microbenchmark(RFun=RFun(x),cppFun=cppFun(x),times=1e5)
Unit: nanoseconds
expr min lq mean median uq max neval cld
RFun 302 357 470.2047 449 513 110152 1e+06 a
cppFun 2330 2598 4045.0059 2729 2879 68752603 1e+06 b
Run Code Online (Sandbox Code Playgroud)
cppFun似乎慢了RFun.为什么会这样?调用函数的时间有所不同吗?或者是运行时间不同的功能本身?是传递和返回参数的时间吗?是否有一些数据转换或数据复制我不知道何时将数据传递给(或从中返回)cppFun?