简体   繁体   中英

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. 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. Also, maxgrp is passed by reference and currgrp is declared each time this function is called.

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

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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