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;
}
此功能已添加到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
相关文章:
- 我正在尝试按降序对地图进行排序,但没有得到预期的结果?
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 如何按矩阵行的总和降序对矩阵进行排序 C++.
- 插入按降序排序
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- 我怎么不能按课程代码的降序对数字进行排序
- 如何使用布尔函数按降序对数组进行排序?
- 如何按降序排序?
- 数组将排序排序为降序而不是升序
- 如何按降序对标准数组进行排序 - C++ 11.
- 按降序C 排序矢量
- 使用QuickSort算法以降序排序向量
- 偶数升序排序,奇数降序排序
- 按类向量的降序排序
- 按降序排序的最佳方式
- 快速排序在对降序-升序数据进行排序时的奇怪行为
- C++使用单独的函数按降序对数组进行排序
- 按降序对双链接列表进行排序
- 对结构、降序或升序的向量进行排序:C++
- 桶排序降序