Rust语言之哈希表

文章目录


Rus设计语言官方教程

哈希表(Hash map)

哈希表也是集合中的一种,也是最常用的集合形式,目前Rust语言核心部分没有对哈希表进行实现,是使用标准库提供的。

一、新建哈希表

rust 复制代码
fn main() {  
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    println!("{:?}",scores); //{"Yellow": 50, "Blue": 10}
}

二、访问某个元素

索引访问

rust 复制代码
fn main() {  
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    println!("value: {}",scores["Blue"]); // 10
}

GET方法

官方教程上的方法

rust 复制代码
fn main() {  
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    let team_name = String::from("Blue");
    let score = scores.get(&team_name).copied().unwrap_or(0);
    println!("value: {}",score); // 10
}

以上两种方法都必须保证访问的元素存在,否则会报错

二、插入新元素

rust 复制代码
fn main() {  
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    println!("{:?}",scores); //{"Yellow": 50, "Blue": 10}
    scores.insert(String::from("Red"), 100);
    println!("{:?}",scores);// {"Red": 100, "Yellow": 50, "Blue": 10}
}

这里可以看出,哈希表中的元素是没有顺序的

三、遍历哈希表

rust 复制代码
fn main() {  
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    for (key, value) in &scores {
        println!("{key}: {value}");
    }
}

=>
Yellow: 50
Blue: 10

四、检查某个元素是否存在

Rust语言中检查哈希表元素是否存在,有两种方法,contains_key方法和entry

  • contains_key方法用于检查HashMap中是否包含特定的键。它返回一个布尔值,指示键是否存在。
  • entry方法用于高效地处理键值对的插入和更新,它返回一个Entry枚举,可以是Occupied(键已存在)或Vacant(键不存在)。

contains_key方法

rust 复制代码
fn main() {  
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    if scores.contains_key("Red"){
        println!("value :{}",scores["Red"]);
    }else {
        println!("Red is not found")
    }
}

=>Red is not found

entry方法

entry方法多用于对值的更新,eor_insert方法在键对应的值存在时就返回这个值的可变引用,如果不存在则将参数作为新值插入并返回新值的可变引用

rust 复制代码
fn main() {  
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    scores.entry(String::from("Red")).or_insert(100);
    scores.entry(String::from("Blue")).or_insert(50);

    println!("{:?}", scores);//{"Blue": 10, "Red": 100, "Yellow": 50}
}

五、元素更新

使用contains_key+insert 的方法

rust 复制代码
fn main() {  
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    let team_list =["Blue","Red"];
    for i in team_list{
        if scores.contains_key(i){
            scores.insert(i.to_string(), scores[i]+50);
        }else{
            scores.insert(i.to_string(), 50);
        }
    }
    println!("{:?}",scores);//{"Red": 50, "Blue": 60, "Yellow": 50}
}

使用entry方法

rust 复制代码
fn main() {  
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    let team_list =["Blue","Red"];
    for i in team_list{
        let count = scores.entry(i.to_string()).or_insert(0);
        *count += 50;
    }
    println!("{:?}",scores);//{"Red": 50, "Blue": 60, "Yellow": 50}
}

相比使用contains_key+insert 的方法,这种方法更优雅。

六、删除元素

rust 复制代码
fn main() {  
    use std::collections::HashMap;

    let mut scores = HashMap::new();
    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);
    scores.insert(String::from("Red"), 80);
    println!("{:?}",scores);//{"Blue": 10, "Yellow": 50, "Red": 80}
    scores.remove("Red");
    println!("{:?}",scores);//{"Blue": 10, "Yellow": 50}
}
相关推荐
pumpkin845149 小时前
Rust 调用 C 函数的 FFI
c语言·算法·rust
蜗牛沐雨10 小时前
警惕 Rust 字符串的性能陷阱:`chars().nth()` 的深坑与高效之道
开发语言·后端·rust
运器12316 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
岁忧16 小时前
(LeetCode 每日一题) 1865. 找出和为指定值的下标对 (哈希表)
java·c++·算法·leetcode·go·散列表
susnm18 小时前
Dioxus 与数据库协作
前端·rust
羊八井19 小时前
类型、分类定义时使用 type 还是 kind ?
rust·typescript·代码规范
Two_brushes.1 天前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
Source.Liu1 天前
【unitrix】 4.18 类型级二进制数加法实现解析(add.rs)
rust
KENYCHEN奉孝1 天前
Rust征服字节跳动:高并发服务器实战
服务器·开发语言·rust
mit6.8242 天前
[Cyclone] 哈希算法 | SIMD优化哈希计算 | 大数运算 (Int类)
算法·哈希算法