C++ sorting and keeping track of indexes

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

    You could sort std::pair instead of just ints - first int is original data, second int is original index. Then supply a comparator that only sorts on the first int. Example:

    Your problem instance: v = [5 7 8]
    New problem instance: v_prime = [<5,0>, <8,1>, <7,2>]
    

    Sort the new problem instance using a comparator like:

    typedef std::pair mypair;
    bool comparator ( const mypair& l, const mypair& r)
       { return l.first < r.first; }
    // forgetting the syntax here but intent is clear enough
    

    The result of std::sort on v_prime, using that comparator, should be:

    v_prime = [<5,0>, <7,2>, <8,1>]
    

    You can peel out the indices by walking the vector, grabbing .second from each std::pair.

提交回复
热议问题