2016-07-29 90 views
2

我可以不按遞減使用RcppRCPP降序排序

升序排序順序排序

NumericVector sortIt(NumericVector v){ 
    std::sort(v.begin(), v.end(), std::greater<int>()); // does not work returns ascending 
    return v; 
} 

NumericVector sortIt(NumericVector v){ 
    std::sort(numbers.rbegin(), numbers.rend()); // errors 
    return v; 
} 
+1

FWIW,一個'RCPP :: NumericVector'是'double's,不'int's一個矢量,所以你可能想用'的std ::更大'。 –

+0

確實,這個工作。謝謝! – JohnCoene

回答

0

這適用於我的鑽機。我不太明白爲什麼。也許比我更合格的人可以準確解釋爲什麼這種方法有效,但其他方式失敗?

library(Rcpp) 

cppFunction('NumericVector sortIt(NumericVector v){ 
    int len = v.size(); 
    std::sort(&v[0], &v[len], std::greater<int>()); 
    return v; 
      }') 

sortIt(sample(1:20)) 
[1] 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 
1

此功能,此後一直added(RCPP版本> = 0.12.7)到Vector成員函數sort。這對於排序CharacterVector對象(升序或降序)是必需的,因爲基礎元素類型需要特殊處理,並且與std::sort + std::greater(以及某些其他STL算法)不兼容。

#include <Rcpp.h> 

// [[Rcpp::export]] 
Rcpp::CharacterVector char_sort(Rcpp::CharacterVector x) { 
    Rcpp::CharacterVector res = Rcpp::clone(x); 
    res.sort(true); 
    return res; 
} 

// [[Rcpp::export]] 
Rcpp::NumericVector dbl_sort(Rcpp::NumericVector x) { 
    Rcpp::NumericVector res = Rcpp::clone(x); 
    res.sort(true); 
    return res; 
} 

請注意使用clone來避免修改輸入向量。


char_sort(c("a", "c", "b", "d")) 
# [1] "d" "c" "b" "a" 

dbl_sort(rnorm(5)) 
# [1] 0.8822381 0.7735230 0.3879146 -0.1125308 -0.1929413