2016-07-29 91 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