Struct std::collections::BTreeMapExperimental
[-]
[+]
[src]
pub struct BTreeMap<K, V> { // some fields omitted }
A map based on a B-Tree.
B-Trees represent a fundamental compromise between cache-efficiency and actually minimizing the amount of work performed in a search. In theory, a binary search tree (BST) is the optimal choice for a sorted map, as a perfectly balanced BST performs the theoretical minimum amount of comparisons necessary to find an element (log2n). However, in practice the way this is done is very inefficient for modern computer architectures. In particular, every element is stored in its own individually heap-allocated node. This means that every single insertion triggers a heap-allocation, and every single comparison should be a cache-miss. Since these are both notably expensive things to do in practice, we are forced to at very least reconsider the BST strategy.
A B-Tree instead makes each node contain B-1 to 2B-1 elements in a contiguous array. By doing this, we reduce the number of allocations by a factor of B, and improve cache efficiency in searches. However, this does mean that searches will have to do more comparisons on average. The precise number of comparisons depends on the node search strategy used. For optimal cache efficiency, one could search the nodes linearly. For optimal comparisons, one could search the node using binary search. As a compromise, one could also perform a linear search that initially only checks every ith element for some choice of i.
Currently, our implementation simply performs naive linear search. This provides excellent
performance on small nodes of elements which are cheap to compare. However in the future we
would like to further explore choosing the optimal search strategy based on the choice of B,
and possibly other factors. Using linear search, searching for a random element is expected
to take O(B logBn) comparisons, which is generally worse than a BST. In practice,
however, performance is excellent. BTreeMap
is able to readily outperform TreeMap
under
many workloads, and is competitive where it doesn't. BTreeMap also generally scales better
than TreeMap, making it more appropriate for large datasets.
However, TreeMap
may still be more appropriate to use in many contexts. If elements are very
large or expensive to compare, TreeMap
may be more appropriate. It won't allocate any
more space than is needed, and will perform the minimal number of comparisons necessary.
TreeMap
also provides much better performance stability guarantees. Generally, very few
changes need to be made to update a BST, and two updates are expected to take about the same
amount of time on roughly equal sized BSTs. However a B-Tree's performance is much more
amortized. If a node is overfull, it must be split into two nodes. If a node is underfull, it
may be merged with another. Both of these operations are relatively expensive to perform, and
it's possible to force one to occur at every single level of the tree in a single insertion or
deletion. In fact, a malicious or otherwise unlucky sequence of insertions and deletions can
force this degenerate behaviour to occur on every operation. While the total amount of work
done on each operation isn't catastrophic, and is still bounded by O(B logBn),
it is certainly much slower when it does.
Methods
impl<K: Ord, V> BTreeMap<K, V>
fn new() -> BTreeMap<K, V>
Makes a new empty BTreeMap with a reasonable choice for B.
fn with_b(b: uint) -> BTreeMap<K, V>
Makes a new empty BTreeMap with the given B.
B cannot be less than 2.
fn clear(&mut self)
Clears the map, removing all values.
Examples
fn main() { use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1u, "a"); a.clear(); assert!(a.is_empty()); }use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1u, "a"); a.clear(); assert!(a.is_empty());
fn find(&self, key: &K) -> Option<&V>
Deprecated: renamed to get
.
fn get<Q>(&self, key: &Q) -> Option<&V>
Returns a reference to the value corresponding to the key.
The key may be any borrowed form of the map's key type, but the ordering on the borrowed form must match the ordering on the key type.
Examples
fn main() { use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); }use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None);
fn contains_key<Q>(&self, key: &Q) -> bool
Returns true if the map contains a value for the specified key.
The key may be any borrowed form of the map's key type, but the ordering on the borrowed form must match the ordering on the key type.
Examples
fn main() { use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); assert_eq!(map.contains_key(&1), true); assert_eq!(map.contains_key(&2), false); }use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); assert_eq!(map.contains_key(&1), true); assert_eq!(map.contains_key(&2), false);
fn find_mut(&mut self, key: &K) -> Option<&mut V>
Deprecated: renamed to get_mut
.
fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
Returns a mutable reference to the value corresponding to the key.
The key may be any borrowed form of the map's key type, but the ordering on the borrowed form must match the ordering on the key type.
Examples
fn main() { use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); match map.get_mut(&1) { Some(x) => *x = "b", None => (), } assert_eq!(map[1], "b"); }use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); match map.get_mut(&1) { Some(x) => *x = "b", None => (), } assert_eq!(map[1], "b");
fn swap(&mut self, key: K, value: V) -> Option<V>
Deprecated: renamed to insert
.
fn insert(&mut self, key: K, value: V) -> Option<V>
Inserts a key-value pair from the map. If the key already had a value
present in the map, that value is returned. Otherwise, None
is returned.
Examples
fn main() { use std::collections::BTreeMap; let mut map = BTreeMap::new(); assert_eq!(map.insert(37u, "a"), None); assert_eq!(map.is_empty(), false); map.insert(37, "b"); assert_eq!(map.insert(37, "c"), Some("b")); assert_eq!(map[37], "c"); }use std::collections::BTreeMap; let mut map = BTreeMap::new(); assert_eq!(map.insert(37u, "a"), None); assert_eq!(map.is_empty(), false); map.insert(37, "b"); assert_eq!(map.insert(37, "c"), Some("b")); assert_eq!(map[37], "c");
fn pop(&mut self, key: &K) -> Option<V>
Deprecated: renamed to remove
.
fn remove<Q>(&mut self, key: &Q) -> Option<V>
Removes a key from the map, returning the value at the key if the key was previously in the map.
The key may be any borrowed form of the map's key type, but the ordering on the borrowed form must match the ordering on the key type.
Examples
fn main() { use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); assert_eq!(map.remove(&1), Some("a")); assert_eq!(map.remove(&1), None); }use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); assert_eq!(map.remove(&1), Some("a")); assert_eq!(map.remove(&1), None);
impl<K, V> BTreeMap<K, V>
fn iter(&'a self) -> Iter<'a, K, V>
Gets an iterator over the entries of the map.
Example
fn main() { use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); map.insert(2u, "b"); map.insert(3u, "c"); for (key, value) in map.iter() { println!("{}: {}", key, value); } let (first_key, first_value) = map.iter().next().unwrap(); assert_eq!((*first_key, *first_value), (1u, "a")); }use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); map.insert(2u, "b"); map.insert(3u, "c"); for (key, value) in map.iter() { println!("{}: {}", key, value); } let (first_key, first_value) = map.iter().next().unwrap(); assert_eq!((*first_key, *first_value), (1u, "a"));
fn iter_mut(&'a mut self) -> IterMut<'a, K, V>
Gets a mutable iterator over the entries of the map.
Examples
fn main() { use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert("a", 1u); map.insert("b", 2u); map.insert("c", 3u); // add 10 to the value if the key isn't "a" for (key, value) in map.iter_mut() { if key != &"a" { *value += 10; } } }use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert("a", 1u); map.insert("b", 2u); map.insert("c", 3u); // add 10 to the value if the key isn't "a" for (key, value) in map.iter_mut() { if key != &"a" { *value += 10; } }
fn into_iter(self) -> IntoIter<K, V>
Gets an owning iterator over the entries of the map.
Examples
fn main() { use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); map.insert(2u, "b"); map.insert(3u, "c"); for (key, value) in map.into_iter() { println!("{}: {}", key, value); } }use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1u, "a"); map.insert(2u, "b"); map.insert(3u, "c"); for (key, value) in map.into_iter() { println!("{}: {}", key, value); }
fn keys(&'a self) -> Keys<'a, K, V>
Gets an iterator over the keys of the map.
Examples
fn main() { use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1u, "a"); a.insert(2u, "b"); let keys: Vec<uint> = a.keys().cloned().collect(); assert_eq!(keys, vec![1u,2,]); }use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1u, "a"); a.insert(2u, "b"); let keys: Vec<uint> = a.keys().cloned().collect(); assert_eq!(keys, vec![1u,2,]);
fn values(&'a self) -> Values<'a, K, V>
Gets an iterator over the values of the map.
Examples
fn main() { use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1u, "a"); a.insert(2u, "b"); let values: Vec<&str> = a.values().cloned().collect(); assert_eq!(values, vec!["a","b"]); }use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1u, "a"); a.insert(2u, "b"); let values: Vec<&str> = a.values().cloned().collect(); assert_eq!(values, vec!["a","b"]);
fn len(&self) -> uint
Return the number of elements in the map.
Examples
fn main() { use std::collections::BTreeMap; let mut a = BTreeMap::new(); assert_eq!(a.len(), 0); a.insert(1u, "a"); assert_eq!(a.len(), 1); }use std::collections::BTreeMap; let mut a = BTreeMap::new(); assert_eq!(a.len(), 0); a.insert(1u, "a"); assert_eq!(a.len(), 1);
fn is_empty(&self) -> bool
Return true if the map contains no elements.
Examples
fn main() { use std::collections::BTreeMap; let mut a = BTreeMap::new(); assert!(a.is_empty()); a.insert(1u, "a"); assert!(!a.is_empty()); }use std::collections::BTreeMap; let mut a = BTreeMap::new(); assert!(a.is_empty()); a.insert(1u, "a"); assert!(!a.is_empty());
impl<K: Ord, V> BTreeMap<K, V>
fn entry(&'a mut self, key: K) -> Entry<'a, K, V>
Gets the given key's corresponding entry in the map for in-place manipulation.
Examples
fn main() { use std::collections::BTreeMap; use std::collections::btree_map::Entry; let mut count: BTreeMap<&str, uint> = BTreeMap::new(); // count the number of occurrences of letters in the vec for x in vec!["a","b","a","c","a","b"].iter() { match count.entry(*x) { Entry::Vacant(view) => { view.set(1); }, Entry::Occupied(mut view) => { let v = view.get_mut(); *v += 1; }, } } assert_eq!(count["a"], 3u); }use std::collections::BTreeMap; use std::collections::btree_map::Entry; let mut count: BTreeMap<&str, uint> = BTreeMap::new(); // count the number of occurrences of letters in the vec for x in vec!["a","b","a","c","a","b"].iter() { match count.entry(*x) { Entry::Vacant(view) => { view.set(1); }, Entry::Occupied(mut view) => { let v = view.get_mut(); *v += 1; }, } } assert_eq!(count["a"], 3u);