C++ sorting and keeping track of indexes

后端 未结 15 2009
甜味超标
甜味超标 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:23

    Beautiful solution by @Lukasz Wiklendt! Although in my case I needed something more generic so I modified it a bit:

    template 
    vector argSort(RAIter first, RAIter last, Compare comp) {
    
      vector idx(last-first);
      iota(idx.begin(), idx.end(), 0);
    
      auto idxComp = [&first,comp](size_t i1, size_t i2) {
          return comp(first[i1], first[i2]);
      };
    
      sort(idx.begin(), idx.end(), idxComp);
    
      return idx;
    }
    

    Example: Find indices sorting a vector of strings by length, except for the first element which is a dummy.

    vector test = {"dummy", "a", "abc", "ab"};
    
    auto comp = [](const string &a, const string& b) {
        return a.length() > b.length();
    };
    
    const auto& beginIt = test.begin() + 1;
    vector ind = argSort(beginIt, test.end(), comp);
    
    for(auto i : ind)
        cout << beginIt[i] << endl;
    

    prints:

    abc
    ab
    a
    

提交回复
热议问题