find the range of all values in a map in rust

To find the range of all values in a hashmap in Rust, we can first retrieve an iterator of all values, then find the maximum and minimum values using the max() and min() functions respectively. Here's an example implementation:

main.rs
use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();

    // insert some key-value pairs
    map.insert("a", 10);
    map.insert("b", 20);
    map.insert("c", 15);
    map.insert("d", 5);

    // get an iterator of all values
    let values = map.values();

    // find the maximum and minimum values
    let max_value = values.clone().max().unwrap();
    let min_value = values.min().unwrap();

    // print the range
    println!("Range of values in map: {} - {}", min_value, max_value);
}
517 chars
22 lines

In this example, we create a new hashmap and insert some key-value pairs. Then we retrieve an iterator of all values using map.values(), and find the maximum and minimum values using max() and min() respectively. Finally, we print the range of values. Note that we need to clone the values iterator before calling max() in order to satisfy the borrowing rules of Rust.

related categories

gistlibby LogSnag