如果在Rcpp中修改IntegerVector的值:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
void test(IntegerVector x) {
x[5] = 77;
}
Run Code Online (Sandbox Code Playgroud)
test()在R中运行函数后:
x <- 10:1
test(x)
print(x) # 10 9 8 7 6 77 4 3 2 1
sum(x) # 55
Run Code Online (Sandbox Code Playgroud)
sum函数返回原始数组的值10:1.我怎么解决这个问题?
使用eg时没有问题x <- sample(10L).
使用SEXP作为函数的参数不允许用户通过简单的分配在它们之间交换数据。我曾经使用tmp缓冲区复制每个值来执行交换。我的问题是:有可能编写仅交换数据的函数,如下所示:
// [[Rcpp::export]]
void swap(SEXP x, SEXP y){
std::swap(x,y);
}
Run Code Online (Sandbox Code Playgroud)
然后,如果我用R运行此函数,x和y将被交换?