C++ sorting and keeping track of indexes

后端 未结 15 2182
甜味超标
甜味超标 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条回答
  •  萌比男神i
    2020-11-22 10:23

    Make a std::pair in function then sort pair :

    generic version :

    template< class RandomAccessIterator,class Compare >
    auto sort2(RandomAccessIterator begin,RandomAccessIterator end,Compare cmp) ->
       std::vector>
    {
        using valueType=typename std::iterator_traits::value_type;
        using Pair=std::pair;
    
        std::vector index_pair;
        index_pair.reserve(std::distance(begin,end));
    
        for(uint32_t idx=0;begin!=end;++begin,++idx){
            index_pair.push_back(Pair(idx,begin));
        }
    
        std::sort( index_pair.begin(),index_pair.end(),[&](const Pair& lhs,const Pair& rhs){
              return cmp(*lhs.second,*rhs.second);
        });
    
        return index_pair;
    }
    

    ideone

提交回复
热议问题