您是否有一些有效的例程来返回带有数组中已排序元素索引的数组?我认为使用 stl vector
存在一些方便的方法.你已经实现了一个没有stl的高效算法,或者你有伪代码或C++代码的参考吗?
Do you have some efficient routine for returning array with indices for sorted elements in a array? I think that some convenient way exists using stl vector
. Do you have already implemented an efficient algo without stl, or do you have a reference to pseudo code or C++ code?
使用 C++11,以下应该可以正常工作:
Using C++11, the following should work just fine:
template <typename T>
std::vector<size_t> ordered(std::vector<T> const& values) {
std::vector<size_t> indices(values.size());
std::iota(begin(indices), end(indices), static_cast<size_t>(0));
std::sort(
begin(indices), end(indices),
[&](size_t a, size_t b) { return values[a] < values[b]; }
);
return indices;
}
这篇关于c ++ sort 跟踪索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!