The beginner tracker stored records in a Vec, in the order they arrived. That breaks down once you need to find a book by ID or list everything by ID: a vector means scanning or sorting each time. The reading queue you will finish on Day 7 needs both answers, and it needs one more guarantee: an ID can be used only once.
BTreeMap<K, V> from std::collections gives you all three. It stores at most one value for each key, finds a key without scanning everything, and always iterates in ascending key order. Unlike HashMap, whose iteration order is unspecified, that makes output identical on every run. The price is a bound on the key type: keys must implement Ord, so the map can compare them.
The tool for enforcing "only once" is the entry API. entry(key) looks the key up once and hands you an Entry, which is either Occupied (the key already has a value) or Vacant (it does not). You match on it and decide what each case means for your program.
Predict and run
Three rows arrive, and two of them use ID 7. Which title stays at key 7? In what order will the keys appear when you loop over the map?
use std::collections::{BTreeMap, btree_map::Entry};
fn main() {
let mut titles = BTreeMap::new();
for (id, title) in [(7, "Rust"), (3, "Types"), (7, "Replacement")] {
match titles.entry(id) {
Entry::Vacant(slot) => { slot.insert(title); }
Entry::Occupied(_) => println!("Duplicate #{id}"),
}
}
for (id, title) in &titles {
println!("#{id} {title}");
}
}Check your prediction
Duplicate #7
#3 Types
#7 RustThe duplicate message prints while the first loop is still running, before any report. The report then lists key 3 before key 7 even though 7 arrived first: insertion order is forgotten, and key order is all that remains. The occupied branch did nothing to the stored value, so Rust survives. Try replacing the whole match with titles.insert(id, title);. Predict the title at key 7 before you run it, then restore the duplicate check.
Why plain insert is the wrong tool here
insert is not wrong in general; it implements a different policy, "last write wins". It replaces any existing value and returns the old one as an Option. You can see the replacement, but only after it has happened.
use std::collections::BTreeMap;
fn main() {
let mut titles = BTreeMap::new();
println!("{:?}", titles.insert(7, "Rust"));
println!("{:?}", titles.insert(7, "Replacement"));
println!("{titles:?}");
}None
Some("Rust")
{7: "Replacement"}The second call returns Some("Rust"), which tells you a value existed, but the map now holds Replacement. With entry, the decision comes before any write. Use insert when overwriting is the behavior you want, such as updating a setting; use entry when the existing value must be protected or combined with the new one.
entry also covers the "combine" case. or_insert(default) returns a mutable reference to the value, inserting the default first if the slot was vacant. That makes counting a one-liner.
use std::collections::BTreeMap;
fn main() {
let mut finished_by_reader = BTreeMap::new();
for reader in ["Mia", "Ada", "Mia", "Mia"] {
*finished_by_reader.entry(reader).or_insert(0) += 1;
}
println!("{finished_by_reader:?}");
}{"Ada": 1, "Mia": 3}The * dereferences the &mut i32 that or_insert returns, so += 1 changes the stored count. Notice that or_insert leaves an existing value alone, which is exactly the keep-the-first policy from the first example. You will use it that way in the checkpoint.
Ask, do not assume
Reading a key that may be missing calls for get, which returns Option<&V>. Indexing with titles[&9] compiles too, but it panics at run time when the key is absent, with the message no entry found for key. In a program that reads IDs from a user, a missing key is an expected input, not a bug, so prefer get and handle None.
The key type is checked at compile time. A BTreeMap needs Ord keys, and floating-point numbers only implement PartialOrd, because NaN is not equal to itself. This does not compile:
use std::collections::BTreeMap;
fn main() {
let mut by_rating = BTreeMap::new();
by_rating.insert(4.5_f64, "Rust");
}The compiler reports error[E0277] and explains that the trait bound f64: Ord is not satisfied. That is the Day 3 trait-bound idea at work inside the standard library. Integers, strings, and your own types that derive Ord, like the queue's BookId, all work as keys.
Name the duplicate policy
Before you write to a map, say which rule you want: keep the first value, keep the last value, or combine them. Then pick the matching tool: an Entry match or or_insert for the first, insert for the last, and or_insert followed by an update for combining.
Practice
Your turn
Write reserve(slots, id, name) so it stores an owned copy of name under id only if the key is free. Return true for a new reservation and false for a duplicate. Reserve key 4 for Ada, then try key 4 again for Grace. Prove that Ada remains at key 4, then print Original reservation kept.
use std::collections::{BTreeMap, btree_map::Entry};
fn main() {
let mut slots: BTreeMap<u32, String> = BTreeMap::new();
// Try two names for key 4 and check the stored name.
println!("Slots: {}", slots.len());
}Hint 1: the idea
Take a mutable map reference. Only the vacant case should build and store an owned String, so a rejected name never allocates.
Hint 2: a first step
Give reserve the parameter types &mut BTreeMap<u32, String>, u32, and &str, then match on slots.entry(id).
Worked solution
use std::collections::{BTreeMap, btree_map::Entry};
fn reserve(slots: &mut BTreeMap<u32, String>, id: u32, name: &str) -> bool {
match slots.entry(id) {
Entry::Vacant(slot) => {
slot.insert(String::from(name));
true
}
Entry::Occupied(_) => false,
}
}
fn main() {
let mut slots = BTreeMap::new();
assert!(reserve(&mut slots, 4, "Ada"));
assert!(!reserve(&mut slots, 4, "Grace"));
assert_eq!(slots.get(&4).map(String::as_str), Some("Ada"));
println!("Original reservation kept");
}Original reservation keptThe function returns a bool so the caller learns what happened without inspecting the map. get yields Option<&String>; mapping it through String::as_str turns that into Option<&str>, which compares directly with Some("Ada"). The Day 7 queue uses this same shape in Queue::add, with an error enum in place of the bool.
Completion is saved in this browser only. It does not measure mastery.