gpt4 book ai didi

c++ - 使用辅助数组的C++比较器排序

转载 作者:行者123 更新时间:2023-12-03 07:15:35 24 4
gpt4 key购买 nike

我有一个无法修改的数组(例如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。在深入探讨之前,需要寻找一些输入。
谢谢。

最佳答案

您的代码按索引在数组中的值排序。因此,输出将在第一个位置具有最小值的索引,在第二个位置具有第二个最小值的索引,依此类推。
为了获得所需的结果,例如,可以执行以下操作:

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

关于c++ - 使用辅助数组的C++比较器排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64570318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com