C++ sorting and keeping track of indexes

后端 未结 15 2272
甜味超标
甜味超标 2020-11-22 10:01

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.<

15条回答
  •  感动是毒
    2020-11-22 10:09

    Using C++ 11 lambdas:

    #include 
    #include 
    #include       // std::iota
    #include     // std::sort, std::stable_sort
    
    using namespace std;
    
    template 
    vector sort_indexes(const vector &v) {
    
      // initialize original index locations
      vector 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;
    }
    

    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.

提交回复
热议问题