相关疑难解决方法(0)

创建排序向量的索引向量

变量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是否有内置功能可以为我高效执行此操作?

c++ stl

15
推荐指数
2
解决办法
2万
查看次数

在 Rcpp 中对命名数字向量进行排序

在一个函数中,我想计算数值,给它们命名并返回一个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 rcpp

9
推荐指数
1
解决办法
155
查看次数

Armadillo C++:根据另外两个向量对向量进行排序

我的问题涉及一个排序练习,我可以在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向量进行此操作?

c++ r vector armadillo rcpp

2
推荐指数
1
解决办法
443
查看次数

标签 统计

c++ ×2

r ×2

rcpp ×2

armadillo ×1

stl ×1

vector ×1