C ++排序和跟踪索引 [英] C++ sorting and keeping track of indexes
问题描述
使用C ++,希望是标准库,我想按升序对一系列样本进行排序,但我也想记住新样本的原始索引。
Using C++, and hopefully the standard library, I want to sort a sequence of samples in ascending order, but I also want to remember the original indexes of the newly samples.
例如,我有一个样本的集合或向量或矩阵 A:[5,2,1,4,3]
。我想把这些排序为 B:[1,2,3,4,5]
,但我也想记住值的原始索引,所以我可以得到另一个集合,其将是:
C:[2,1,4,3,0]
- 其对应于'B中的每个元素的索引
For example, I have a set, or vector, or matrix of samples A : [5, 2, 1, 4, 3]
. I want to sort these to be B : [1,2,3,4,5]
, but I also want to remember the original indexes of the values, so I can get another set which would be:
C : [2, 1, 4, 3, 0 ]
- which corresponds to the index of the each element in 'B', in the original 'A'.
例如,在Matlab中,您可以:
For example, in Matlab you can do:
[a,b]=sort([5, 8, 7])
a = 5 7 8
b = 1 3 2
任何人都可以看到一个好的方法来做这个?
Can anyone see a good way to do this?
推荐答案
使用C ++ 11 lambdas
Using C++11 lambdas
template <typename T>
vector<size_t> sort_indexes(const vector<T> &v) {
// initialize original index locations
vector<size_t> idx(v.size());
iota(idx.begin(), idx.end(), 0);
// sort indexes based on comparing values in v
sort(idx.begin(), idx.end(),
[&v](size_t i1, size_t i2) {return v[i1] < v[i2];});
return idx;
}
现在,您可以在迭代中使用返回的索引向量,例如
Now you can use the returned index vector in iterations such as
for (auto i: sort_indexes(v)) {
cout << v[i] << endl;
}
显然,你也可以选择提供自己的原始索引向量, ,比较器或使用额外向量在sort_indexes函数中自动重新排序v。
Obviously, you can also choose to supply your own original index vector, sort function, comparator, or automatically reorder v in the sort_indexes function using an extra vector.
这篇关于C ++排序和跟踪索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!