I cannot sort in descending order using Rcpp
Sort in ascending order:
NumericVector sortIt(NumericVector v){
std::sort(v.begin(), v.end());
return v;
}
Attempt to sort in descending order:
NumericVector sortIt(NumericVector v){
std::sort(v.begin(), v.end(), std::greater<int>()); // does not work returns ascending
return v;
}
and
NumericVector sortIt(NumericVector v){
std::sort(numbers.rbegin(), numbers.rend()); // errors
return v;
}
This functionality has since been added (Rcpp version >= 0.12.7) to the Vector member function sort. This is necessary for sorting CharacterVector objects in particular (either ascending or descending) because the underlying element type requires special handling, and is incompatible with std::sort + std::greater (as well as certain other STL algorithms).
#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;
}
Note the use of clone to avoid modifying the input vector.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With