首页 > 解决方案 > c++比较器排序使用辅助数组

问题描述

values我有一个无法修改的数组(比如)。我想知道这个数组中的值是否已排序,它们最终的位置/索引是什么。所以,为此我只是使用如下代码:

#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;
}

实际输出

2 3 4 5 6 7 8 9 10 0 1

预期输出

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

我试图理解为什么输出如上所示。看起来 STL 使用IntroSort. 在我深入挖掘之前寻找一些输入。

谢谢。

标签: c++sortinglambdastl

解决方案


您的代码按它们在数组中的值对索引进行排序。因此输出将在第一个位置具有最小值的索引,在第二个位置具有第二小的索引,依此类推。

为了得到你想要的,你可以,例如,执行以下操作:

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

推荐阅读