c++ - 基于大小的向量的向量排序索引
问题描述
我有一个向量向量,我想按每个向量的大小对其进行排序。我想将排序向量的索引放在另一个向量中,我不想更改主向量。我怎么能那样做?我想使用排序函数,但我在排序函数中找不到任何参数来确定我想使用每个内容的大小和存储索引对其进行排序。
我试试这个,但它有一个错误。
在 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
我认为是因为第三个论点。
解决方案
根据另一个容器的内容构建排序表需要自定义函子或捕获 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();
});
}
推荐阅读
- c# - 为什么属性是公共的,而 setter 是私有的
- android - 如何从应用程序目录(在 android 文件夹内)获取 Arraylist 中的所有音频
- r - 位置抖动的 geom_errorbar 问题
- php - Laravel:无法在刀片文件中显示图像
- ruby-on-rails - 如何比较宝石版本?
- google-signin - 调用 https://oauth2.googleapis.com/token 超时
- javascript - Discord.js 机器人加入然后离开
- ios - 可以使用不是 rootViewController 的 NavigationController 来访问和更新 Appdelegate.m 中的 UIWindow 类吗?
- c - 将结构与 null 进行比较的操作数无效
- java - 使用 BroadCastReceiver 重新启动后应用服务不会启动