c++ - 如何获得 vector 的排序索引?

标签 c++ algorithm sorting vector

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

最佳答案

您正在寻找的称为标记排序(或索引排序)。这是在 C++11 中使用 lambda 的最小示例:

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

Live on Coliru

关于c++ - 如何获得 vector 的排序索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37732275/

相关文章:

c++ - 允许对 C++11 中的循环进行编译器优化

c++ - C++中的Lua匿名函数存储

c++ - c++中Dijkstra的段错误

algorithm - 这种愚蠢的最坏情况下的时间复杂度?

C:链表的合并排序,合并子数组在排序函数中未正确捕获

c++ - 我应该为赋值运算符使用左值引用限定符吗?

c++ - 在 C++ 中,如何检查一个数字是否可以被 2*M_PI 整除?

algorithm - IDA* 是否与使用启发式函数的 IDS 相同?

.net - 在深度优先搜索期间检测系谱图中的循环

arrays - 如何根据 Ruby 中另一个数组的值对散列进行排序?