Flexible-size arma vector allocation - true in general or is a property of Rcpp?

StackOverflow https://stackoverflow.com//questions/23044537

  •  21-12-2019
  •  | 
  •  

Question

I'm using Rcpp package to write a code that has the main proportion written in C++ and the smaller proportion in R.

Based on what I know from C++, all unlike R, all variables in C++ should be declared upfront and this declaration includes both type and size. For instance when we say:

arma::vec test(2);

then I assume test is an armadillo vector with size 2 which means we should not assign anything of a different size to test. Is that right?

Here is my challenge:

In my code, I have a loop that assigns vectors of different size (usually larger than 2) to the "test vector" without redeclaration of test . To my surprise, the code works perfectly fine without any compiling error !

In each iteration, here is how I assign a new vector to test:

test = Rcpp::as<arma::vec>(myList["aVecFromMyList"]);

Question:

Is that an Armadillo feature that we can assign vectors of different lengths to test which is initially declared to be of size 2? or it's an Rcpp package feature?

Thanks very much for your help.

Was it helpful?

Solution

You're asking for the size of the vector to be encoded into the type. When you specify that something is of type arma::vec, you allow it to accept arma::vecs of any size.

If you want to enforce a size constraint in the type, then you want something like arma::vec::fixed<N>, where in your case N would be 2. This is a type that enforces the constraint that vectors should be of size N. There are also typedefs for low-digit versions of these, e.g. vec2 as a fixed vector of size 2.

You would have to modify your as call similarly I believe -- hopefully it works, I haven't tested it.

You should read the Armadillo docs; the Armadillo docs are probably some of the cleanest and most useful out there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top