C++ sorting and keeping track of indexes

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

    I wrote generic version of index sort.

    template 
    void argsort(RAIter iterBegin, RAIter iterEnd, Compare comp, 
        std::vector& indexes) {
    
        std::vector< std::pair > pv ;
        pv.reserve(iterEnd - iterBegin) ;
    
        RAIter iter ;
        size_t k ;
        for (iter = iterBegin, k = 0 ; iter != iterEnd ; iter++, k++) {
            pv.push_back( std::pair(k,iter) ) ;
        }
    
        std::sort(pv.begin(), pv.end(), 
            [&comp](const std::pair& a, const std::pair& b) -> bool 
            { return comp(*a.second, *b.second) ; }) ;
    
        indexes.resize(pv.size()) ;
        std::transform(pv.begin(), pv.end(), indexes.begin(), 
            [](const std::pair& a) -> size_t { return a.first ; }) ;
    }
    

    Usage is the same as that of std::sort except for an index container to receive sorted indexes. testing:

    int a[] = { 3, 1, 0, 4 } ;
    std::vector indexes ;
    argsort(a, a + sizeof(a) / sizeof(a[0]), std::less(), indexes) ;
    for (size_t i : indexes) printf("%d\n", int(i)) ;
    

    you should get 2 1 0 3. for the compilers without c++0x support, replace the lamba expression as a class template:

    template  
    class PairComp {
    public:
      Compare comp ;
      PairComp(Compare comp_) : comp(comp_) {}
      bool operator() (const std::pair& a, 
        const std::pair& b) const { return comp(*a.second, *b.second) ; }        
    } ;
    

    and rewrite std::sort as

    std::sort(pv.begin(), pv.end(), PairComp(comp)()) ;
    

提交回复
热议问题