[英]How to get the sorted index of a vector?
I have a vector. 我有一个矢量。 It is not sorted. 它没有排序。 Now I want to get its indices which will sort the vector. 现在我想获得它将对矢量进行排序的索引。 For example vector<int> v{1, 3, 2}
, sorted indices are {0, 2, 1}
because v[0] <= v[2] <= v[1]
. 例如, vector<int> v{1, 3, 2}
1,3,2 vector<int> v{1, 3, 2}
,排序的索引是{0, 2, 1}
因为v[0] <= v[2] <= v[1]
。 If two equal, doesn't matter which one go first. 如果两个相等,那么首先去哪个并不重要。
What you're looking for is called tag sorting (or index sorting). 您正在寻找的是标签排序(或索引排序)。 Here is a minimal example using lambdas in C++11: 这是在C ++ 11中使用lambdas的最小示例:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.