C++ 排序和跟踪索引

C++ sorting and keeping track of indexes(C++ 排序和跟踪索引)

本文介绍了C++ 排序和跟踪索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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 new samples.

例如,我有一个样本集、向量或矩阵 A : [5, 2, 1, 4, 3].我想将这些排序为 B : [1,2,3,4,5],但我也想记住值的原始索引,所以我可以获得另一个集合:C : [2, 1, 4, 3, 0 ] - 对应于原始'A'中'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 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 个 lambda:

Using C++ 11 lambdas:

#include <iostream>
#include <vector>
#include <numeric>      // std::iota
#include <algorithm>    // std::sort, std::stable_sort

using namespace std;

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
  // using std::stable_sort instead of std::sort
  // to avoid unnecessary index re-orderings
  // when v contains elements of equal values 
  stable_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.

You can also choose to supply your original index vector, sort function, comparator, or automatically reorder v in the sort_indexes function using an extra vector.

这篇关于C++ 排序和跟踪索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++ 排序和跟踪索引

基础教程推荐