在对象向量中的对象字段排序
Sorting by a Object field in a Vector of Vector of Objects
我的 Edge 对象中有一个vector<vector<Edge> >graph
,我有 3 个称为高度权重长度的 int 字段。我已经用元素填充了我的向量,现在我想根据权重从大到小对向量进行排序。我怎么能这样做。
假设Edge
看起来像
struct Edge {
int height, weight, length;
}
添加一个函数,例如
bool compareWeight(const Edge& l, const Edge& r) {
return l.weight > r.weight;
}
并使用算法中的sort
for(int i = 0; i < graph.size(); i++) {
std::sort(graph[i].begin(), graph[i].end(), compareWeight);
}
这将按重量对Edge
的每个向量进行排序。
为此,
您的类Edge
必须具有重载运算符<
。然后你可以只使用#include <algorithm>
中的sort()
sort(graph.begin(), graph.end());
重载其他运算符作为>
、>=
、<=
、==
、!=
也是有意义的。
相关文章:
- 私有字段对象与私有继承?
- 如何正确实例化静态字段 tat 是另一个类对象
- 为什么最后一个推回向量的对象的字段会转移到向量的其他对象?
- 对象引用中的字段以不同的方法返回不同的值
- 基于不同字段的对象向量的排序功能
- 如何从具有多个对象/字段的类中调用方法函数
- 在对象向量中的对象字段排序
- 函数上的关键字'const'意味着对象字段完全只读?
- 使所有TU已知的静态对象字段的值
- 作为对象字段的右值引用
- 如何有效地从该对象中包含的另一个对象访问对象字段/属性
- 使用 ADO 将原始文件数据插入访问表的 BLOB("OLE 对象")字段
- 将对象字段的值放置在变量中的性能
- 如何将对象字段作为函数参数(特征向量)传递
- 对象字段返回对象本身,而不是存储在字段中的实例
- 通过提及对象本身返回对象字段
- 在Visual Studio 2013中使用c++中的对象字段数据创建图表
- 无法设置静态对象字段的值(错误LNK2001:未解析的外部符号)
- 在循环中填充C++对象字段会导致空字段
- 为什么这可以让我获得一个指向常量对象字段的非常量指针