How to compare tuples that contain a float?

I'm aware that there is no total ordering for floats. Meaning, sorting an vector of floats usually looks like

fn main() {
    let mut fs = vec![1.0, 1.5, 1.1, 1.2, 0.1];
    fs.sort_by(|a, b| a.partial_cmp(b).unwrap());
    assert_eq!(fs, vec![0.1, 1.0, 1.1, 1.2, 1.5])
}

What is a good way to achieve the same with a vector of tuples that have a float in them?

fn main() {
    let ts = vec![(1, 1.0, false), (2, 0.5, true), (1, 0.5, true), (2, 0.5, false)];
    fs.sort_by(|a, b| ???);
    assert_eq!(ts, vec![(1, 0.5, true), (1, 1.0, false), (2, 0.5, false), (2, 0.5, true)])
}

partial_cmp still works. Rust Playground

3 Likes

Oh my :person_facepalming: I was under the impression that .partial_cmp is a float "method". But this works on every type that implements the PartialOrd trait, right? And tuple does.

1 Like

Correct.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.