Using colon (':') to access elements in an array in C++ (in Rcpp)

佐手、 提交于 2019-12-10 14:42:25

问题


I am trying to run the following code. Frankly I know C++ only little but I want to get the following function run. Can you help me run this silly example?

cppFunction(
  'NumericVector abc(int x, int x_end, NumericVector y)
  {
    NumericVector z;
    int x1 = x + x_end;
    z = y[x:x1];
    return(z);  
   }'
)

abc(3,c(0,1,10,100,1000,10000))

I see this ...

error: expected ']' before ':' token

Update Sorry I forgot to mention that I need to generate a sequence of numbers from x to x1. The function IntegerVector::create only creates a variable with only x and x1 not x though x1. The example I gave was trivial. I updated the example now. I need to do in C++ what seq() does in R

Solution based on the answer below (@SleuthEye)

Rcpp::cppFunction(
  'NumericVector abc(int x, int x_end, NumericVector y)
  {
  NumericVector z;
  Range idx(x,x_end);
  z = y[idx];
  return(z);  
  }'
)

abc(3,5,c(0,1,10,100,1000,10000))
[1]   100  1000 10000

回答1:


The code argument to Rcpp's cppFunction must include valid C++ code. The library tries to make as seamless as possible, but is still restricted to the syntax of C++. More specifically, C++ does not have a range operator (:) and correspondingly the C++ compiler tells you that the indexing expression must be a valid index (enclosed within [], without the :). The type of the index could be an int or IntegerVector, but it cannot contain the : character.

As suggesting in Rcpp subsetting article, you may however create a vector which represent the desired (x,x+1) range which you can then use to index NumericVector variables as such:

IntegerVector idx = IntegerVector::create(x, x+1);
z = y[idx];

More generally, you can use a Range in a similar fashion:

Range idx(x, x1);
z = y[idx];


来源:https://stackoverflow.com/questions/30063951/using-colon-to-access-elements-in-an-array-in-c-in-rcpp

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