详解Rust标准库:HashMap
查看本地官方文档
安装rust
后运行
rustup doc
查看The Standard Library
即可获取标准库内容
std::collections::hash_map::HashMap定义
哈希表又称散列表,是一种键 - 值(key - value
)对的数据结构,也被称为关联数组或字典。它主要用于存储和快速检索基于特定键的数据
这里使用 std::collections::hash_map::HashMap
:使用二次探测和 SIMD 查找实现的哈希映射
HashMap
定义
// 指定hash器为RandomState
pub struct HashMap<K, V, S = RandomState> {
// 实现了具体的哈希映射功能
base: base::HashMap<K, V, S>,
}
方法
with_capacity
:创建一个指定初始容量的哈希表
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::with_capacity(10);
hash_map.insert("key1", "value1");
println!("with_capacity: {:?}", hash_map);
// with_capacity: {"key1": "value1"}
}
with_hasher
:使用自定义哈希器创建哈希表
use std::{ collections::HashMap, hash::RandomState };
fn main() {
let s = RandomState::new();
let mut map = HashMap::with_hasher(s);
map.insert(1, 2);
println!("{}", map.get(&1).unwrap());
// 2
}
with_capacity_and_hashe
:同时指定初始容量和哈希器
use std::{ collections::HashMap, hash::RandomState };
fn main() {
let s = RandomState::new();
let mut map = HashMap::with_capacity_and_hasher(10, s);
map.insert(1, 2);
println!("{}", map.get(&1).unwrap());
// 2
println!("{}", map.capacity());
// 14
}
capacity
:返回哈希表的当前容量
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::new();
hash_map.insert("key4", "value4");
println!("capacity: {}", hash_map.capacity());
// capacity: 3
}
keys
:返回一个迭代器,遍历哈希表的键
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::new();
hash_map.insert("key4", "value4");
for key in hash_map.keys() {
println!("key: {}", key);
}
// key: key4
}
into_keys
:将哈希表的键提取为一个可迭代的集合
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::new();
hash_map.insert("key1", "value1");
hash_map.insert("key2", "value2");
hash_map.insert("key3", "value3");
hash_map.insert("key4", "value4");
let keys_iterable: Vec<_> = hash_map.into_keys().collect();
println!("into_keys: {:?}", keys_iterable);
// into_keys: ["key3", "key2", "key1", "key4"]
}
values
:返回一个迭代器,遍历哈希表的值
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::new();
hash_map.insert("key1", "value1");
hash_map.insert("key2", "value2");
hash_map.insert("key3", "value3");
hash_map.insert("key4", "value4");
// values: 返回一个迭代器,遍历哈希表的值。
for value in hash_map.values() {
println!("value: {}", value);
}
// value: value3
// value: value1
// value: value2
// value: value4
}
values_mut
:返回一个可变迭代器,允许修改哈希表的值
use std::collections::HashMap;
fn main() {
let mut map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for val in map.values_mut() {
*val = *val + 10;
}
for val in map.values() {
println!("{val}");
}
// 11
// 12
// 13
}
into_values
:将哈希表的值提取为一个可迭代的集合
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::new();
hash_map.insert("key1", "value1");
hash_map.insert("key2", "value2");
hash_map.insert("key3", "value3");
hash_map.insert("key4", "value4");
let values_iterable: Vec<_> = hash_map.into_values().collect();
println!("into_values: {:?}", values_iterable);
// into_values: ["value1", "value2", "value3", "value4"]
}
iter
:返回一个迭代器,遍历哈希表的键值对
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::new();
hash_map.insert("key1", "value1");
hash_map.insert("key2", "value2");
hash_map.insert("key3", "value3");
hash_map.insert("key4", "value4");
for (key, value) in hash_map.iter() {
println!("key: {}, value: {}", key, value);
}
// 每次结果不一样
}
iter_mut
:返回一个可变迭代器,允许修改哈希表的键值对
use std::collections::HashMap;
fn main() {
let mut map = HashMap::from([
("a", 1),
("b", 2),
("c", 3),
]);
for (_, val) in map.iter_mut() {
*val *= 2;
}
for (key, val) in &map {
println!("key: {key} val: {val}");
}
// key: a val: 2
// key: b val: 4
// key: c val: 6
}
len
:返回哈希表中键值对的数量
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::new();
hash_map.insert("key1", "value1");
hash_map.insert("key2", "value2");
hash_map.insert("key3", "value3");
hash_map.insert("key4", "value4");
println!("length: {}", hash_map.len());
// length: 4
}
is_empty
:判断哈希表是否为空
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::new();
hash_map.insert("key1", "value1");
hash_map.insert("key2", "value2");
hash_map.insert("key3", "value3");
hash_map.insert("key4", "value4");
println!("is empty: {}", hash_map.is_empty());
// is empty: false
}
drain
:移除并返回哈希表中的所有键值对
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::new();
hash_map.insert("key1", "value1");
hash_map.insert("key2", "value2");
hash_map.insert("key3", "value3");
hash_map.insert("key4", "value4");
let drained: Vec<_> = hash_map.drain().collect();
println!("drained: {:?}", drained);
// drained: [("key4", "value4"), ("key1", "value1"), ("key3", "value3"), ("key2", "value2")]
}
retain
:保留满足给定谓词的键值对
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::from([
("key1", "value1"),
("key2", "value2"),
]);
// 返回包含 "value1" 的键值对
hash_map.retain(|_, value| value.contains("value1"));
println!("retained map: {:?}", hash_map);
// retained map: {"key1": "value1"}
}
clear
:清空哈希表
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::from([
("key1", "value1"),
("key2", "value2"),
]);
hash_map.clear();
println!("cleared map: {:?}", hash_map);
// cleared map: {}
}
hasher
:返回哈希表使用的哈希器
use std::collections::HashMap;
fn main() {
let hash_map = HashMap::from([
("key1", "value1"),
("key2", "value2"),
]);
let hasher = hash_map.hasher();
println!("hasher: {:?}", hasher);
// hasher: RandomState { .. }
}
reserve
:预先分配足够的空间,以至少容纳指定数量的额外元素
use std::collections::HashMap;
fn main() {
let mut hash_map: HashMap<i32, String> = HashMap::new();
hash_map.reserve(10);
println!("reserved map capacity: {}", hash_map.capacity());
// reserved map capacity: 14
}
try_reserve
:尝试预先分配足够的空间,以至少容纳指定数量的额外元素,如果容量已经足够,则不执行任何操作
use std::collections::HashMap;
fn main() {
let mut hash_map = HashMap::from([
("key1", "value1"),
("key2", "value2"),
("key3", "value3"),
]);
hash_map.try_reserve(1).expect("why is the test harness OOMing on a handful of bytes?");
println!("reserved map capacity: {}", hash_map.capacity());
// reserved map capacity: 7
}
shrink_to_fit
:释放哈希表中未使用的空间,使其容量与长度匹配
use std::collections::HashMap;
fn main() {
let mut map = HashMap::with_capacity(20);
map.insert("key", "value");
map.shrink_to_fit();
println!("shrunk map capacity: {}", map.capacity());
// shrunk map capacity: 3
}
shrink_to
:将哈希表的容量减少到指定的大小,如果当前容量小于指定大小,则不进行操作
use std::collections::HashMap;
fn main() {
let mut map = HashMap::with_capacity(20);
map.insert("key", "value");
map.shrink_to(10);
println!("shrunk to map capacity: {}", map.capacity());
// shrunk to map capacity: 14
}
entry
:返回一个 Entry API,可以用于插入或更新键值对
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
// 如果键不存在,则插入新值,否则返回现有值的可变引用
let entry = map.entry("key").or_insert("value");
println!("entry value: {}", entry);
// entry value: value
}
get
:返回指定键对应的值的不可变引用,如果键不存在则返回 None
use std::collections::HashMap;
fn main() {
let map = HashMap::from([("key", "value")]);
if let Some(value) = map.get("key") {
println!("get value: {}", value);
// get value: value
}
}
get_key_value
:返回指定键对应的值和键的不可变引用,如果键不存在则返回 None
use std::collections::HashMap;
fn main() {
let map = HashMap::from([("key", "value")]);
if let Some((_, value)) = map.get_key_value("key") {
println!("get_key_value value: {}", value);
// get_key_value value: value
}
}
contains_key
:判断哈希表中是否存在指定的键
use std::collections::HashMap;
fn main() {
let map = HashMap::from([("key", "value")]);
println!("contains key: {}", map.contains_key("key"));
// contains key: true
}
get_mut
:返回指定键对应的值的可变引用,如果键不存在则返回 None
use std::collections::HashMap;
fn main() {
let mut map = HashMap::from([("key", "value")]);
if let Some(value) = map.get_mut("key") {
*value = "modified_value";
}
println!("get_mut value: {}", map.get("key").unwrap());
// get_mut value: modified_value
}
insert
:插入一个键值对到哈希表中,如果键已经存在,则覆盖旧值
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("key", "value");
map.insert("key", "new_value");
println!("inserted map: {:?}", map);
// inserted map: {"key": "new_value"}
}
remove
:移除指定键对应的键值对,并返回被移除的值,如果键不存在则返回 None
use std::collections::HashMap;
fn main() {
let mut map = HashMap::from([("key", "value")]);
if let Some(value) = map.remove("key") {
println!("removed value: {}", value);
// removed value: value
}
}
remove_entry
:移除指定键对应的键值对,并返回被移除的键值对,如果键不存在则返回None
use std::collections::HashMap;
fn main() {
let mut map = HashMap::from([("key", "value")]);
if let Some((key, value)) = map.remove_entry("key") {
println!("removed entry key: {}, value: {}", key, value);
// removed entry key: key, value: value
}
}