简体   繁体   中英

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. 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 < . And then you can just use sort() from #include <algorithm>

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

Also make sense to overload other operators as > , >= , <= , == , != .

Assuming Edge looks something like

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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