Edge is a class with 3 fields: weight, from_vertex, to_vertex. I want to create a set containing all unique edges in a graph. (If from_vertex and to_vertex are swapped -and weights are equal-, it is still the same edge.) Also, I want this set be sorted by weights of the edges. Is this possible with a set implementation or is there a better way?
Sure, it's possible. But only because you don't actually need two comparators.
The basic idea is to lexically sort on the tuple <weight, min_vertex, max_vertex>
, where min_vertex
is the lesser of to_vertex
or from_vertex
, and max_vertex
is the greater. Two opposing edges with the same weight will have the same tuple, of course, and two opposing edges without the same weight will be distinct. The set will overall be sorted by weight, since that's the most significant element of the tuple.
One thing that this doesn't get you is the ability to search for an edge if you know the from,to
but don't know the weight. Similarly, it doesn't make all the edges for a particular from,to
pair consecutive (which, of course, would be incompatible with sorting by weight). If you want that sort of thing, you'll probably need to maintain multiple structures.