简体   繁体   中英

c++ comparator sorting using auxillary array

I have an array (say values ) that that cannot be modified. I want to know if the values in this array are sorted what will be their eventual position/index. So, for this I am simply using code as below:

#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>

int main() {
    std::vector<unsigned> position(11, 0);
    std::iota(position.begin(), position.end(), 0);
    std::vector<unsigned> values = {140, 141, 118, 119, 122, 123, 128, 129, 133, 134, 138, 139};
    
    auto value_comparator = [&values](const unsigned& index1, const unsigned& index2) {
        return (values[index1] < values[index2]);
    };
    
    std::sort(position.begin(), position.end(), value_comparator);
    
    for (auto val : position) {
        std::cout << val << " ";
    }
    std::cout << std::endl;

    return 0;
}

Actual Output :

2 3 4 5 6 7 8 9 10 0 1

Expected Output :

10 11 0 1 2 3 4 5 6 7 8 9

I am trying to understand why the output is as shown above. Looks like STL uses IntroSort . Looking for some input before I dig deeper.

Thanks.

Your code sorts the indices by their value in the array. So the output will have at the first position the index of the smallest value, in the second the index of the second-smallest and so on.

To get what you want out of that, you can, for example, do the following:

std::vector<unsigned> result(position.size());
for(unsigned i = 0; i < position.size(); ++i) {
    result[position[i]] = i;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM