c++ sort keeping track of indices

algorithm, c++, sorting, stl

Solution

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

Problem

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?

Original source

Related problems