【问题标题】:sorting index of vector of vector based on size [closed]基于大小的向量的向量排序索引[关闭]
【发布时间】:2021-07-15 13:32:15
【问题描述】:

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

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

在 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

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

【问题讨论】:

  • 什么错误? Edit 全文引用。
  • 什么是tree?应该从哪里供应?您是否想使用 lambda 捕获来引用它,而不是传递 std::sort() 无法处理的第三个参数?
  • @underscore_d 我编辑了
  • 试试std::sort(sort_tree.begin(), sort_tree.end(),[&amp;tree](const int &amp; a, const int&amp; b) { return tree[a].size() &lt; tree[b].size();});
  • @jabaa 哦,它有效。谢谢:)

标签: c++ algorithm sorting vector


【解决方案1】:

根据另一个容器的内容构建排序表需要自定义函子或捕获 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();
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    相关资源
    最近更新 更多