0

How to find to order a vector of tuples based on the last value (which is a f64) of the tuple, with rust? I have a big vector with tuples, so I'm looking for an efficient way to order this vector.

pub fn main() {
    let mut results = vec![
        ("a".to_string(), 50,  5.0),
        ("b".to_string(), 70, 4.0),
        ("c".to_string(), 40, 10.0)
    ];
}
hups
  • 133
  • 1
  • 1
  • 5
  • just loop over the vector... – Netwave Dec 13 '21 at 21:51
  • @Netwave Sorry, I've rephrased my question. – hups Dec 13 '21 at 21:52
  • @Chris Not really, it's not related to tuples. Also the answer is related to integers. – hups Dec 13 '21 at 22:04
  • You may find useful infomation, in particular about `sort_by` in that question and its answers. – Chris Dec 13 '21 at 22:07
  • This [other answer](https://stackoverflow.com/a/67707591/574531) on the linked duplicate explains what you need to do if you have types that aren't inherently sortable or if you otherwise need custom ordering rules. – Herohtar Dec 13 '21 at 22:30

1 Answers1

1

You can use sort_by and f64::partial_cmp to order them:

pub fn main() {
    let mut results = vec![
        ("a".to_string(), 50,  5.0),
        ("b".to_string(), 70, 4.0),
        ("c".to_string(), 40, 10.0)
    ];

    results.sort_by(|a, b| a.2.partial_cmp(&b.2).unwrap());
    
    println!("{:?}", results);
}

This will panic on values like inf or NaN since they cannot be ordered, but cases like those should be easy enough to handle outside of the closure if needed.

Jeremy Meadows
  • 2,314
  • 1
  • 6
  • 22