Skip to content

Instantly share code, notes, and snippets.

@mjhanninen
Created January 4, 2022 07:03
Show Gist options
  • Save mjhanninen/ef9876c426c05ea21b45df69ba4c94bc to your computer and use it in GitHub Desktop.
Save mjhanninen/ef9876c426c05ea21b45df69ba4c94bc to your computer and use it in GitHub Desktop.
Examples on how Rust's VecDeque::binary_search_by behaves

Examples on how binary_search_by behaves

use std::collections::VecDeque;

fn main() {
    let ex = |q: &VecDeque<i32>, y: i32, desc: &str| {
        println!("search({}) -> {:?}\t# {}", y, q.binary_search_by(|&x| x.cmp(&y)), desc);
    };
    let q = VecDeque::from([1, 2, 3, 5, 6, 7]);
    println!("q = {:?}", q);
    println!("q.len() = {:?}", q.len());
    ex(&q, 0, "the left \"underflow\" yields an error at 0");
    ex(&q, 1, "the first member yields an okay at the same index 0");
    ex(&q, 4, "a missing member an error at the index it would be inserted in");
    ex(&q, 5, "and the next member yields an okay at that same index");
    ex(&q, 100, "the right \"overflow\" yields an error with the index equal to q.len()");
}
q = [1, 2, 3, 5, 6, 7]
q.len() = 6
search(0) -> Err(0)     # the left "underflow" yields an error at 0
search(1) -> Ok(0)      # the first member yields an okay at the same index 0
search(4) -> Err(3)     # a missing member an error at the index it would be inserted in
search(5) -> Ok(3)      # and the next member yields an okay at that same index
search(100) -> Err(6)   # the right "overflow" yields an error with the index equal to q.len()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment