簡體   English   中英

Rcpp中的Rcpp Quicksort錯誤?

[英]Rcpp Quicksort error in R?

我正在使用RCPP為quicksort構建C ++函數quicksort。 我正在嘗試通過R中的cxxfunction編譯和加載此函數。我需要使用cxxFunction。 我在R中收到以下消息:

錯誤:無法將參數'1'的'Rcpp :: IntegerVector {aka Rcpp :: Vector <13,Rcpp :: PreserveStorage>}'轉換為'int *',使'int quicksort(int *,int,int)'使: *** [file15ecb338ec.o]錯誤1

誰能告訴我這是怎么了?

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)

只是為了看看我是否可以使用cxxfunction調用遞歸函數,我創建了一個階乘函數,並通過cxxfunction進行了調用,它運行良好。

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)

問題恰恰是編譯器所說的。 您的函數需要一個int*但您要傳遞給它一個Rcpp::IntegerVector 查看Rcpp::IntegerVector文檔 ,您可以通過.begin()檢索原始指針,因此可以通過quicksort(arr.begin(), a, b)調用。

另外,除非您真的需要滾動自己的quicksort,否則我將只使用標准庫的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) )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM