【发布时间】:2023-02-23 07:49:25
【问题描述】:
我有一个向量。它没有排序。现在我想得到它的索引,它将对向量进行排序。例如vector<int> v{1, 3, 2},排序后的索引是{0, 2, 1},因为v[0] <= v[2] <= v[1]。如果两个相等,哪个先走并不重要。
【问题讨论】:
标签: c++ algorithm sorting vector
我有一个向量。它没有排序。现在我想得到它的索引,它将对向量进行排序。例如vector<int> v{1, 3, 2},排序后的索引是{0, 2, 1},因为v[0] <= v[2] <= v[1]。如果两个相等,哪个先走并不重要。
【问题讨论】:
标签: c++ algorithm sorting vector
您正在寻找的是标签排序(或索引排序)。这是在 C++11 中使用 lambda 的最小示例:
#include <algorithm>
#include <numeric>
#include <iostream>
#include <vector>
template<typename T>
std::vector<std::size_t> tag_sort(const std::vector<T>& v)
{
std::vector<std::size_t> result(v.size());
std::iota(std::begin(result), std::end(result), 0);
std::sort(std::begin(result), std::end(result),
[&v](const auto & lhs, const auto & rhs)
{
return v[lhs] < v[rhs];
}
);
return result;
}
int main()
{
std::vector<char> v{'a', 'd', 'b', 'c'};
auto idxs = tag_sort(v);
for (auto && elem : idxs)
std::cout << elem << " : " << v[elem] << std::endl;
}
【讨论】: