如何获取向量的排序索引?

use*_*020 5 c++ sorting algorithm vector

我有一个矢量.它没有排序.现在我想获得它将对矢量进行排序的索引.例如vector<int> v{1, 3, 2},排序的索引是{0, 2, 1}因为v[0] <= v[2] <= v[1].如果两个相等,那么首先去哪个并不重要.

vso*_*tco 10

您正在寻找的是标签排序(或索引排序).这是在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;
}
Run Code Online (Sandbox Code Playgroud)

Live on Coliru