c++ - 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
. 在我深入挖掘之前寻找一些输入。
谢谢。
解决方案
您的代码按它们在数组中的值对索引进行排序。因此输出将在第一个位置具有最小值的索引,在第二个位置具有第二小的索引,依此类推。
为了得到你想要的,你可以,例如,执行以下操作:
std::vector<unsigned> result(position.size());
for(unsigned i = 0; i < position.size(); ++i) {
result[position[i]] = i;
}
推荐阅读
- git - 在同一 Jenkins 管道中的下一个新代理中,如何在最后结束的代理中获取自定义环境变量(使用 AWS 代码提交 Jenkins 项目)
- asp.net-core-webapi - .net 核心 Web API 允许的所有特殊字符
- javascript - 而循环在较高的输出期间挂起
- c++ - 如何使while循环在上升时保持递增
- material-ui - 如何访问主题工具栏断点属性?
- docker - 我可以在基于容器的 Azure 批处理池中使用 docker 卷吗
- javascript - 如何使用 performance.measureMemory() API 进行前端可观察性?
- powershell - 如何创建嵌套数组并在其中添加数组元素?
- formatting - 重置项目以具有一致的间距约定
- r - 重新排序数据框的行