首页 > 解决方案 > 基于大小的向量的向量排序索引

问题描述

我有一个向量向量,我想按每个向量的大小对其进行排序。我想将排序向量的索引放在另一个向量中,我不想更改主向量。我怎么能那样做?我想使用排序函数,但我在排序函数中找不到任何参数来确定我想使用每个内容的大小和存储索引对其进行排序。

我试试这个,但它有一个错误。

在 sort_tree 我存储从 0 到 n-1 的索引(n 是二维数组的大小)

树是我的二维数组。

std::sort(sort_tree.begin(), sort_tree.end(),
          [](const int & a, const int& b, vector<vector<int>> tree) {
              return tree[a].size() < tree[b].size();
          });

错误是:

Error C2228 left of '.size' must have class/struct/union

我认为是因为第三个论点。

标签: c++algorithmsortingvector

解决方案


根据另一个容器的内容构建排序表需要自定义函子或捕获 lambda。后者如下图所示。

#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>

int main()
{
    std::vector<std::vector<int>> tree;

    // fill tree with whatever

    // build index table.
    std::vector<int> idx(tree.size());
    std::iota(idx.begin(), idx.end(), 0);

    // sort with capturing lambda
    std::sort(idx.begin(), idx.end(), [&tree](int lhs, int rhs)
    {
        return tree[lhs].size() < tree[rhs].size();
    });
}

推荐阅读