详解Rust标准库:BTreeMap
std::collections::BTreeMap定义
B树也称B-树
,注意不是减号,是一棵多路平衡查找树;理论上,二叉搜索树 (BST) 是最佳的选择排序映射,但是每次查找时层数越多I/O次数越多,B 树使每个节点都包含连续数组中的 B-1 到 2B-1 元素,可以减少树的高度,减少I/O次数
BTreeMap
定义
pub struct BTreeMap<K, V, A: Allocator + Clone = Global> {
// B 树的根节点
root: Option<Root<K, V>>,
// B 树映射中存储的键值对的数量
length: usize,
// 分配器
pub(super) alloc: ManuallyDrop<A>,
// PhantomData是一个零大小的类型,用于向编译器提供类型信息,但在运行时不占用任何空间
_marker: PhantomData<crate::boxed::Box<(K, V), A>>,
}
方法
clear
:用于清空BTreeMap
,移除所有的键值对
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::new();
map.insert("a", 1);
map.insert("b", 2);
map.clear();
println!("After clear, is empty? {}", map.is_empty());
// After clear, is empty? true
}
get
:用于获取指定键对应的值的不可变引用,如果键不存在则返回None
use std::collections::BTreeMap;
fn main() {
let map = BTreeMap::from([
("a", 1),
("b", 2),
]);
if let Some(value) = map.get("a") {
println!("Value for 'a': {}", value);
// Value for 'a': 1
} else {
println!("'a' not found.");
}
}
get_key_value
:返回指定键对应的值和键的不可变引用,如果键不存在则返回None
use std::collections::BTreeMap;
fn main() {
let map = BTreeMap::from([
("a", 1),
("b", 2),
]);
if let Some((key, value)) = map.get_key_value("b") {
println!("Key-value pair for 'b': {} -> {}", key, value);
// Key-value pair for 'b': b -> 2
} else {
println!("'b' not found.");
}
}
first_key_value
:返回BTreeMap
中的第一个键值对,如果地图为空则返回None
use std::collections::BTreeMap;
fn main() {
let map = BTreeMap::from([
("a", 1),
("b", 2),
]);
if let Some((first_key, first_value)) = map.first_key_value() {
println!("First key-value pair: {} -> {}", first_key, first_value);
// First key-value pair: a -> 1
} else {
println!("Map is empty.");
}
}
first_entry
:返回一个可变引用到BTreeMap
中的第一个键值对,如果地图为空则返回None
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::from([
("a", 1),
("b", 2),
]);
if let Some(first_entry) = map.first_entry() {
println!("First entry: {} -> {}", first_entry.key(), first_entry.get());
// First entry: a -> 1
} else {
println!("Map is empty.");
}
}
pop_first
:移除并返回BTreeMap
中的第一个键值对,如果地图为空则返回None
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::from([
("a", 1),
("b", 2),
]);
if let Some((popped_key, popped_value)) = map.pop_first() {
println!("Popped first pair: {} -> {}", popped_key, popped_value);
// Popped first pair: a -> 1
} else {
println!("Map is empty.");
}
}
pop_last
:移除并返回BTreeMap
中的最后一个键值对,如果地图为空则返回None
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::from([
("a", 1),
("b", 2),
]);
if let Some((last_key, last_value)) = map.pop_last() {
println!("Popped last pair: {} -> {}", last_key, last_value);
// Popped last pair: b -> 2
} else {
println!("Map is empty.");
}
}
contains_key
:判断BTreeMap
中是否存在指定的键
use std::collections::BTreeMap;
fn main() {
let map = BTreeMap::from([
("a", 1),
("b", 2),
]);
println!("Contains 'a'? {}", map.contains_key("a"));
// Contains 'a'? true
}
get_mut
:返回指定键对应的值的可变引用,如果键不存在则返回None
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::from([
("a", 1),
("b", 2),
]);
if let Some(value) = map.get_mut("a") {
*value = 3;
println!("Modified value for 'a': {}", value);
// Modified value for 'a': 3
} else {
println!("'a' not found.");
}
}
insert
:插入一个键值对到BTreeMap
中,如果键已经存在,则覆盖旧值
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::new();
map.insert("a", 1);
map.insert("a", 2);
println!("After insert: {:?}", map);
// After insert: {"a": 2}
}
remove
:移除指定键对应的键值对,并返回被移除的值,如果键不存在则返回None
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::from([
("a", 1),
("b", 2),
]);
if let Some(removed_value) = map.remove("a") {
println!("Removed value for 'a': {}", removed_value);
// Removed value for 'a': 1
} else {
println!("'a' not found.");
}
}
remove_entry
:移除指定键对应的键值对,并返回被移除的键值对,如果键不存在则返回None
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::from([
("a", 1),
("b", 2),
]);
if let Some((removed_key, removed_value)) = map.remove_entry("b") {
println!("Removed entry: {} -> {}", removed_key, removed_value);
// Removed entry: b -> 2
} else {
println!("'b' not found.");
}
}
retain
:保留满足给定谓词的键值对
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
map.retain(|key, value| (*key > "b" || *value >= 2));
println!("After retain: {:?}", map);
// After retain: {"b": 2, "c": 3}
}
append
:将另一个BTreeMap
的键值对追加到当前BTreeMap
中
use std::collections::BTreeMap;
fn main() {
let mut map1 = BTreeMap::from([
("a", 1),
("b", 2),
]);
let mut map2 = BTreeMap::from([
("c", 3),
("d", 4),
]);
map1.append(&mut map2);
println!("After append: {:?}", map1);
// After append: {"a": 1, "b": 2, "c": 3, "d": 4}
}
range
:返回一个迭代器,遍历BTreeMap
中满足给定范围条件的键值对
use std::collections::BTreeMap;
fn main() {
let map = BTreeMap::from([
("a", 1),
("b", 2),
("c", 3),
("d", 4),
]);
for (key, value) in map.range("b"..) {
println!("In range: {} -> {}", key, value);
}
// In range: b -> 2
// In range: c -> 3
// In range: d -> 4
}
range_mut
:返回一个可变迭代器,遍历BTreeMap
中满足给定范围条件的键值对,并允许修改值
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::from([
("a", 1),
("b", 2),
("c", 3),
("d", 4),
]);
for (key, value) in map.range_mut("b"..) {
*value = *value * 2;
println!("Modified in range: {} -> {}", key, value);
}
// Modified in range: b -> 4
// Modified in range: c -> 6
// Modified in range: d -> 8
}
entry
:返回一个Entry API
,可以用于插入或更新键值对
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::new();
let entry = map.entry("a").or_insert(1);
println!("Entry value for 'a': {}", entry);
// Entry value for 'a': 1
}
split_off
:移除并返回给定键及其对应的值,如果键不存在则返回None
和一个空BTreeMap
into_keys
:将BTreeMap
的键提取为一个可迭代的集合
use std::collections::BTreeMap;
fn main() {
let map = BTreeMap::from([
("a", 1),
("b", 2),
]);
let keys: Vec<_> = map.into_keys().collect();
println!("Keys: {:?}", keys);
// Keys: ["a", "b"]
}
into_values
:将BTreeMap
的值提取为一个可迭代的集合
use std::collections::BTreeMap;
fn main() {
let map = BTreeMap::from([
("a", 1),
("b", 2),
]);
let values: Vec<_> = map.into_values().collect();
println!("Values: {:?}", values);
// Values: [1, 2]
}
iter
:返回一个迭代器,遍历BTreeMap
的键值对
use std::collections::BTreeMap;
fn main() {
let map = BTreeMap::from([
("a", 1),
("b", 2),
]);
for (key, value) in map.iter() {
println!("Iter: {} -> {}", key, value);
}
// Iter: a -> 1
// Iter: b -> 2
}
iter_mut
:返回一个可变迭代器,允许修改BTreeMap
的键值对
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::from([
("a", 1),
("b", 2),
]);
for (key, value) in map.iter_mut() {
*value = *value * 2;
println!("Mut iter: {} -> {}", key, value);
}
// Mut iter: a -> 2
// Mut iter: b -> 4
}
keys
:返回一个迭代器,遍历BTreeMap
的键
use std::collections::BTreeMap;
fn main() {
let map = BTreeMap::from([
("a", 1),
("b", 2),
]);
for key in map.keys() {
println!("Key from keys: {}", key);
}
// Key from keys: a
// Key from keys: b
}
values
:返回一个迭代器,遍历BTreeMap
的值
use std::collections::BTreeMap;
fn main() {
let map = BTreeMap::from([
("a", 1),
("b", 2),
]);
for value in map.values() {
println!("Value from values: {}", value);
}
// Value from values: 1
// Value from values: 2
}
values_mut
:返回一个可变迭代器,允许修改BTreeMap
的值
use std::collections::BTreeMap;
fn main() {
let mut map = BTreeMap::from([
("a", 1),
("b", 2),
]);
for value in map.values_mut() {
*value = *value * 3;
println!("Mut value from values_mut: {}", value);
}
// Mut value from values_mut: 3
// Mut value from values_mut: 6
}
len
:返回BTreeMap
中键值对的数量
use std::collections::BTreeMap;
fn main() {
let map = BTreeMap::from([
("a", 1),
("b", 2),
]);
println!("Length: {}", map.len());
// Length: 2
}
is_empty
:判断BTreeMap
是否为空
use std::collections::BTreeMap;
fn main() {
let map: BTreeMap<i32, &str> = BTreeMap::new();
println!("Is empty: {}", map.is_empty());
// Is empty: true
}