Rcpp Copy a vector to a vector

爷,独闯天下 提交于 2019-12-04 08:09:56

As hinted in the comment, you could use

Grp1 = clone(Grp2) ;

but this will create a new R object that then get assigned to Grp1, so you pay for some memory allocation and you discard some memory that could have been used, i.e. more work for the garbage collector down the line.

You could also just reuse the existing memory from Grp1 with std::copy

std::copy( Grp2.begin(), Grp2.end(), Grp1.begin() ) ;

Another way that is perhaps over the top is to use sapply. Something like this:

auto identity = [](double x){ return x; } ;
Grp1 = sapply( Grp2, identity );

But given Rcpp does not sapply over lambdas, you'd probably have to define identity outside your function for this approach to be useable.

inline double identity(double x){ 
    return x ;
}

FWIW, in Rcpp14 or Rcpp11, you could simply do:

Grp1 = import(Grp2) ;

What is currently happening is a very common error with pointers. Grp1 and Grp2 are pointers, so setting one equal to the other means that they point to the same array (and any changes to one array will affect the other). One solution would be to use a iterator to copy all values over one at a time. This would be done by emptying one IntegerVector by popping all values and then pushing all elements from the other IntegerVector into the emptied IntegerVector.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!