indexmap-rs / indexmap

A hash table with consistent order and fast iteration; access items by key or sequence index
https://docs.rs/indexmap/
Other
1.71k stars 150 forks source link

Add method to get a map entry by index #290

Closed bkragl closed 9 months ago

bkragl commented 10 months ago

This change adds a method get_index_entry to IndexMap, which is the by-index counterpart to entry. The returned struct IndexedEntry provides the same methods as OccupiedEntry, except replace_key.

A concrete use case where I found this useful is having a map: IndexMap<_, Vec<_>> with the invariant that each Vec is non-empty. Imagine we want to pick an entry at a random index and pop a value from the Vec. Without this change we'd have to use get_mut_index and swap_remove_index, and ensure that we use the same index. With get_index_entry we can write:

let mut e = map.get_index_entry(index).unwrap();
let v = e.get_mut();
let x = v.pop().unwrap();
if v.is_empty() {
    e.swap_remove();
}