Use std::cmp::Reverse with binary_search_by_key

Viewed 527

How to use std::cmp::Reverse with binary_search_by_key? Example: Rust-Playground

The documentation to Rust's Vec::binary_search_by_key says:

Assumes that the slice is sorted by the key, for instance with sort_by_key using the same key extraction function.

In the minimal example below, I am using the same extraction function -- but no luck.

use std::cmp::Reverse;

fn main() {
    let mut v = vec![1, 2, 3, 4, 5];

    v.sort_by_key(|&num| Reverse(num));
    println!("{:?}", v);
    let index = v.binary_search_by_key(&1, |&num| Reverse(num));
    println!("Res: {:?}", index);
}

This complains about mismatched types: "expected integer, found struct std::cmp::Reverse".

error[E0308]: mismatched types
 --> src/main.rs:8:51
  |
8 |     let index = v.binary_search_by_key(&1, |&num| Reverse(num));
  |                                                   ^^^^^^^^^^^^ expected integer, found struct `std::cmp::Reverse`
  |
  = note: expected type `{integer}`
           found struct `std::cmp::Reverse<{integer}>`

1 Answers

Careful inspection of the function signature gives the answer.

pub fn binary_search_by_key<'a, B, F>(
    &'a self,
    b: &B,
    f: F
) -> Result<usize, usize> where
    B: Ord,
    F: FnMut(&'a T) -> B, 

B is the return value of the function, and also the first argument (after &self).

Therefore we have to add Reverse to the first argument as well:

v.binary_search_by_key(&Reverse(1), |&num| Reverse(num))
Related