C ++排序跟踪指数指数

2023-09-10 22:44:25 作者:假装你还在

你有一些有效的例程用于返回数组指数在一个数组排序的元素呢?我认为,一些方便的方式中存在使用STL的载体。你已经实现了一个高效的算法中没有STL,或者你有一个裁判伪code或C ++ code?

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 ref 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;
}