简体   繁体   English

Rcpp,C ++:通过引用传递一个改变大小的整数向量

[英]Rcpp, C++: Pass by reference for a vector of integers changing size

I just started learning Rcpp (a R and C++ interface) yesterday to make my code run faster, and I am learning a lot from all of you reading the posts. 我昨天刚开始学习Rcpp(一个R和C ++界面),以使我的代码运行得更快,而且我从你们所有人那里学到了很多东西。 Thanks! 谢谢! I am just wondering if it would cause a problem if I assign a vector of lower size to a vector passed by reference. 我只是想知道如果我将一个较小尺寸的矢量分配给通过引用传递的向量,它是否会引起问题。

if(currValue > maxValue){
  maxgrp = currgrp;
  maxValue = currValue;
}

where maxgrp is, say, declared as a IntegerVector of size 5 and the size of currgrp is changing in some recursive algorithm, but it would not exceed the size of maxgrp as initially declared. 例如,maxgrp声明为大小为5的IntegerVector,而currgrp的大小在某些递归算法中正在改变,但它不会超过最初声明的maxgrp的大小。 Also, maxgrp is passed by reference and currgrp is declared each time this function is called. 此外,maxgrp通过引用传递,每次调用此函数时都会声明currgrp。

After all, the return value seemed to be correct for several test runs, but I am wondering I will be encountering some unexpected errors in the long run. 毕竟,几次测试运行的返回值似乎是正确的,但我想知道从长远来看我会遇到一些意想不到的错误。

Thank you 谢谢

If you use RcppArmadillo, define all your vectors using arma and then you can do for instance 如果您使用RcppArmadillo,请使用arma定义所有向量,然后您可以执行此操作

// I'm assuming currgrp is rowvector of arma type

// I'm assuming maxgrp is rowvector of arma type

int ncurrgrp = 1; if(currValue > maxValue){ ncurrgrp = currgrp.n_rows; maxgrp(arma::span(0,ncurrgrp-1) = currgrp; }

In this way you are sure that you fill the first ncurrgrp elements of maxgrp with the elements of currgrp. 通过这种方式,您可以确保使用currgrp元素填充maxgrp的第一个ncurrgrp元素。

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

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