【问题标题】:c++ comparator sorting using auxillary arrayc++比较器排序使用辅助数组
【发布时间】:2021-02-10 16:03:50
【问题描述】:

我有一个无法修改的数组(比如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。在深入挖掘之前寻找一些输入。

谢谢。

【问题讨论】:

  • 对我来说这看起来很像正确的输出,你为什么会期望例如第一个索引是10 和11,其中关联的值是138 和139,它们不是values 中的最低值?!
  • @lubgr 10 和 11 显示140 排序位置是10 和141 排序位置是11。
  • @RachitAgrawal 这不是您的代码所做的。您的代码对第二个数组进行排序与​​第一个数组中的值相关。因此,索引0 处的2 表明第二个数组中位置2 的值是排序后的第一个元素。
  • @super 的意思是你的输出显示了值的原始索引。
  • 谢谢大家。没想到。

标签: c++ sorting lambda stl


【解决方案1】:

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

要从中得到你想要的,例如,您可以执行以下操作:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多