Grazosi
Grazosi

Reputation: 703

Finding smallest key value in btreemap, when the key is a tuple

I have a btreemap like this:

use alloc::collections::BTreeMap;
let mut map: BTreeMap<(u16,u16), [u8;32]> = BTreeMap::new();

and just for the sake of example, I add these elements:

map.insert((1,3), [0;32]);
map.insert((5,3), [1;32]);
map.insert((7,3), [2;32]);
map.insert((2,3), [3;32]);
map.insert((10,3), [4;32]);

Now, the keys here are tuples. What I need to do, is to find the smallest key value. But based on the first element of the key tuple.

A totally naive solution would be:

let mut n = 5000;
for pair in map.keys(){
    if pair.0 < n{
        n = pair.0;
    }
}
println!("n {}", n);

But is there a nicer way of doing this same thing? Maybe more efficient?

Upvotes: 1

Views: 1163

Answers (1)

cdhowie
cdhowie

Reputation: 169008

BTreeMaps are already sorted by key, and tuples implement ordering traits when all of their component types do. Tuples are ordered by their first element, then their second, and so on. Therefore, you can just grab the first key in the map:

let smallest = map.keys().next().map(|v| v.0);

This will give you an Option<u16> containing the first tuple field of the first (and therefore smallest) key in the map, or None if the map is empty.

Upvotes: 1

Related Questions