简体   繁体   English

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

[英]Sorting by a Object field in a Vector of Vector of Objects

I have a vector<vector<Edge> >graph in my Edge object i have 3 int fields called height weight length. 我的Edge对象中有一个vector<vector<Edge> >graph ,我有3个int字段,称为height weight length。 I have already populated my vector with elements and now i want to sort my vector in terms of weight from largest to smallest. 我已经用元素填充了向量,现在我想按权重从大到小对向量进行排序。 How would i be able to do so. 我将如何做到这一点。

To do so your class Edge must have overloaded operator < . 为此,您的Edge类必须重载了运算符< And then you can just use sort() from #include <algorithm> 然后您可以只使用#include <algorithm> sort()

sort(graph.begin(), graph.end());

Also make sense to overload other operators as > , >= , <= , == , != . 将其他运算符重载为>>=<===!=也很有意义。

Assuming Edge looks something like 假设Edge看起来像

struct Edge {
    int height, weight, length;
}

Add a function like 添加类似的功能

bool compareWeight(const Edge& l, const Edge& r) {
    return l.weight > r.weight;
}

And use sort from algorithm 并使用算法 sort

for(int i = 0; i < graph.size(); i++) {
    std::sort(graph[i].begin(), graph[i].end(), compareWeight);
}

That will sort each vector of Edge 's by weight. 这将按权重对Edge的每个向量进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM