简体   繁体   中英

Rcpp Quicksort error in R?

I am using RCPP to build a C++ function quicksort for quicksort. I am trying to compile and load this function through the cxxfunction in R. I need to use the cxxFunction. I am getting the following message in R:

error: cannot convert 'Rcpp::IntegerVector {aka Rcpp::Vector<13, Rcpp::PreserveStorage>}' to 'int*' for argument '1' to 'int quicksort(int*, int, int)' make: *** [file15ecb338ec.o] Error 1

Can anyone tell me what is wrong with this?

incl <- 'int quicksort(int xx[], int left, int right) {

int i = left; 
int j = right;
int tmp;
int pivot = xx[(left + right) / 2];

/* partition */
while (i <= j) {
while (xx[i] < pivot)
i++;
while (xx[j] > pivot)
j--;
if (i <= j) {
tmp = xx[i];
xx[i] = xx[j];
xx[j] = tmp;
i++;
j--;
}
}

/* recursion */
if (left < j){
quicksort(xx, left, j);
}
if (i < right){
quicksort(xx, i, right);
}

return (quicksort(xx,i,j));
}
'
sortCpp <- cxxfunction(signature( x = "integer",left = "integer",
                                  right = "integer"),
                       body = 'IntegerVector arr(x);
                       int a = as<int>(left);
                       int b = as<int>(right);
                       return wrap(quicksort(arr,a,b));',
                       include = incl,
                       plugin = "Rcpp",
                       verbose = TRUE)

Just to see if I could call a recursive function using cxxfunction I created a factorial function and called this through cxxfunction and it worked fine.

incl <- 'int factorial(int n)
{
  return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}
'


factcpp <- cxxfunction(signature( x = "integer"),
                       plugin = "Rcpp",
                       include = incl,
                       body = 'int xnew = as<int>(x);
                       return wrap( factorial(x) );
                       ',
                       verbose = TRUE)

The problem is exactly what the compiler says. Your function expects an int* but you are passing it an Rcpp::IntegerVector . Looking at the documentation for Rcpp::IntegerVector , you can retrieve the raw pointer by .begin() , so you would call via quicksort(arr.begin(), a, b) .

Also, unless you really need to roll your own quicksort, I would just use the Standard Library's std::sort :

src <- 'Rcpp::IntegerVector v = Rcpp::IntegerVector(vp);
        std::sort(v.begin(), v.end());
        return wrap(v);'
fun <- cxxfunction(signature(vp="integer"), body=src, plugin="Rcpp")
fun( c(5, 2, 7, -3) )

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