C++ sorting and keeping track of indexes

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

    Well, my solution uses residue technique. We can place the values under sorting in the upper 2 bytes and the indices of the elements - in the lower 2 bytes:

    int myints[] = {32,71,12,45,26,80,53,33};
    
    for (int i = 0; i < 8; i++)
       myints[i] = myints[i]*(1 << 16) + i;
    

    Then sort the array myints as usual:

    std::vector myvector(myints, myints+8);
    sort(myvector.begin(), myvector.begin()+8, std::less());
    

    After that you can access the elements' indices via residuum. The following code prints the indices of the values sorted in the ascending order:

    for (std::vector::iterator it = myvector.begin(); it != myvector.end(); ++it)
       std::cout << ' ' << (*it)%(1 << 16);
    

    Of course, this technique works only for the relatively small values in the original array myints (i.e. those which can fit into upper 2 bytes of int). But it has additional benefit of distinguishing identical values of myints: their indices will be printed in the right order.

提交回复
热议问题