How do I sort a `Vec<(f32, f32)>`

If there an easier way to sort a Vec<(f32, f32)> by sorting by the first element of the tuple, and fall back to the second if they are equals than this?

    let mut my_vec: Vec<(f32, f32)> = /* ... */;
    my_vec.sort_by(|&a, &b| {
        let cmp = a.0.partial_cmp(&b.0).unwrap();
        if cmp != Ordering::Equal {
            return cmp;

All the values I have in my vec are "normal numbers" (no +/-infinity, NaN, …), so I'm totally fine with unwrap of equivalent.

Note: sort() doesn't works since f32 doesn't implement Ord.

vec.sort_by(|x, y| x.partial_cmp(y).unwrap());

should work since tuples implement lexicographical ordering.


Since you know additional information that the type system cannot prove, .unwrap() is the usual way to go.

It's just that I didn't thought I could call partial_cmp on the tuple itself instead of the elements of the tuple.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.