我无法使用降序排序Rcpp
按升序排序:
NumericVector sortIt(NumericVector v){
std::sort(v.begin(), v.end());
return v;
}
Run Code Online (Sandbox Code Playgroud)
尝试按降序排序:
NumericVector sortIt(NumericVector v){
std::sort(v.begin(), v.end(), std::greater<int>()); // does not work returns ascending
return v;
}
Run Code Online (Sandbox Code Playgroud)
和
NumericVector sortIt(NumericVector v){
std::sort(numbers.rbegin(), numbers.rend()); // errors
return v;
}
Run Code Online (Sandbox Code Playgroud)
此功能已添加(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;
}
Run Code Online (Sandbox Code Playgroud)
请注意使用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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1431 次 |
| 最近记录: |