Rcpp降序排序

Rcpp sort descending

本文关键字:排序 降序 Rcpp      更新时间:2023-10-16

我无法使用Rcpp 按降序排序

按升序排序:

NumericVector sortIt(NumericVector v){
    std::sort(v.begin(), v.end());
    return v;
}

尝试按降序排序:

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;
}

此功能已添加到Vector成员函数sort中(Rcpp版本>=0.1.27)。这对于对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

这适用于我的装备。我不太明白为什么。也许有比我更有资格的人可以准确地解释为什么这种配方有效,但其他配方却失败了?

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