当前位置: 首页 > article >正文

详解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
}

http://www.kler.cn/a/385201.html

相关文章:

  • 大数据分库分表方案
  • 优先队列(基于无序数组,有序数组,堆)
  • 【C】无类型指针及函数指针
  • Spring Boot中集成MyBatis操作数据库详细教程
  • 水资源遥测终端机助力灌区信息化建设
  • Java | Leetcode Java题解之第546题移除盒子
  • go 集成gorm 数据库操作
  • npm install慢
  • ORACLE 删除archivelog日志
  • 最佳实践:如何实现函数参数之间的TS类型相依赖和自动推断
  • 基于微信小程序的电子购物系统的设计与实现(lw+演示+源码+运行)
  • Vue动态计算Table表格的高度
  • Spring Security(5.x, 6.x ) RBAC访问控制
  • 深入解析 WinForms MVVM 模式中的事件驱动与数据驱动
  • maven打jar包知识-运行包、依赖包、传递性
  • 解析json导出csv或者直接入库
  • 音频内容理解
  • 爱奇艺大数据多AZ统一调度架构:打破数据孤岛,提升效率
  • 【系统架构设计师】高分论文:论软件的可用性设计
  • 如何快速搭建一个spring boot项目
  • FIPS203 后量子安全ML-KEM(标准简读)
  • .vue文件中定义变量和在引用的.ts文件中定义变量的区别
  • C++模拟真人动态生成鼠标滑动路径
  • 29种Prompt Engineering
  • 自监督学习:机器学习的未来新方向
  • Docker篇(阿里云私服)