在对象向量中的对象字段排序

Sorting by a Object field in a Vector of Vector of Objects

本文关键字:对象 字段 排序 向量      更新时间:2023-10-16

我的 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());

载其他运算符作为>>=<===!=也是有意义的。