c ++排序跟踪索引

kir*_*off 24 c++ sorting algorithm stl

你有一些有效的例程来返回数组中带有索引的数组吗?我认为使用stl向量存在一些方便的方法.你是否已经实现了一个没有stl的高效算法,或者你有一个伪代码或C++代码的参考?

感谢致敬

Kon*_*lph 37

使用C++ 11,以下应该可以正常工作:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 在C++ 11中,您可以使用`std :: iota`来填充向量增加的值. (5认同)

Pub*_*bby 7

你可以尝试这样的事情:

template<typename C>
class index_sorter {
  public:
    compare(C const& c) : c(c) {}
    bool operator()(std::size_t const& lhs, std::size_t const& rhs) const {
      return c[lhs] < c[rhs];
    }
  private:
    C const& c;
};

std::sort(index_vector.begin(), index_vector.end(), index_sorter(vector));
Run Code Online (Sandbox Code Playgroud)