变量x是一个nint 的向量,我想按升序对向量进行排序.但是,由于这个问题范围之外的原因,我想要保持不变.因此,x我想创建另一个n索引向量,而不是实际排序内容,其中每个索引引用相应的值x,如果x已经排序的话.
例如:
std::vector<int> x = {15, 3, 0, 20};
std::vector<int> y;
// Put the sorted indices of x into the vector y
for (int i = 0; i < 4; i++)
{
std::cout << y[i];
}
Run Code Online (Sandbox Code Playgroud)
应该给出输出:
2
1
0
3
Run Code Online (Sandbox Code Playgroud)
对应于x中的值:
0
3
15
20
Run Code Online (Sandbox Code Playgroud)
我可以想到很多及时实现这一点的方法,但我想知道STL是否有内置功能可以为我高效执行此操作?
在一个函数中,我想计算数值,给它们命名并返回一个NumericVector在 Rcpp 中排序的值。我可以对向量进行排序(使用this),但值名称的顺序保持不变。
library(Rcpp)
x <- c(a = 1, b = 5, c = 3)
cppFunction('
NumericVector foo(NumericVector x) {
std::sort(x.begin(), x.end());
return(x);
}')
foo(x)
## a b c
## 1 3 5
Run Code Online (Sandbox Code Playgroud)
我希望函数返回这个:
## a c b
## 1 3 5
Run Code Online (Sandbox Code Playgroud)
是否可以?我怎样才能做到这一点?
我的问题涉及一个排序练习,我可以在R中轻松地(但可能很慢)进行,并希望用C++进行,以加快我的代码.
考虑三个相同大小的矢量a,b和c.在R中,以下命令首先按照b对数字进行排序,然后,在关系的情况下,将根据c进一步排序.
a<-a[order(b,c),1]
Run Code Online (Sandbox Code Playgroud)
例:
a<-c(1,2,3,4,5)
b<-c(1,2,1,2,1)
c<-c(5,4,3,2,1)
> a[order(b,c)]
[1] 5 3 1 4 2
Run Code Online (Sandbox Code Playgroud)
有没有一种有效的方法在C++中使用Armadillo向量进行此操作?