Rcpp降序排序

Rcpp sort descending

我无法使用 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;
}

这适用于我的装备。我不太明白为什么。也许比我更有资格的人可以准确解释为什么这行得通,但其他公式却失败了?

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

此功能已 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