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);
}

访问某个元素

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"]); // 存在则打印,不存在会panic
}
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");
    // scores.get(&team_name): 
    // 在scores哈希表(或者Dictionary)中查找对应team_name键(key)的值,返回的是一个Option类型
    // .copied(): 
    // Option类型上的方法,如果里面的值存在(在这里即scores.get(&team_name)查找到的值),就复制一个相同的值出来
    // .unwrap_or(0): 
    // 返回Option中包含的值或者一个默认值
    //
    // 如果使用如下方式,则报错:called `Option::unwrap()` on a `None` value
    // let team_name = String::from("Blue1");
    // let score = scores.get(&team_name).copied().unwrap();
    let score = scores.get(&team_name).copied().unwrap_or(0);
    println!("value: {}",score); // 10
}

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

fn main() {
   
	use std::collections::HashMap;
	let mut map = HashMap::new();
	map.insert(1, "a");
	assert_eq!(map.get(&1), Some(&"a"));
	assert_eq!(map.get(&2), None);
}

插入新元素

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

哈希表中的元素没有顺序

遍历哈希表

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}");
    }
}

检查某个元素是否存在

两种方法,contains_key和entry

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

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")
    }
}

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

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

元素更新

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}
}
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 ,这种方法更优雅

删除元素

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("Red1");
    println!("{:?}",scores);//{"Blue": 10, "Yellow": 50, "Red": 80}
    scores.remove("Red");
    println!("{:?}",scores);//{"Blue": 10, "Yellow": 50}
}

相关推荐

  1. rust

    2024-02-19 20:42:02       48 阅读
  2. Rust语言之

    2024-02-19 20:42:02       63 阅读
  3. STL容器之补充——桶实现

    2024-02-19 20:42:02       45 阅读
  4. C#中(Hashtable)

    2024-02-19 20:42:02       55 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-19 20:42:02       91 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-19 20:42:02       97 阅读
  3. 在Django里面运行非项目文件

    2024-02-19 20:42:02       78 阅读
  4. Python语言-面向对象

    2024-02-19 20:42:02       88 阅读

热门阅读

  1. CSS background-size

    2024-02-19 20:42:02       55 阅读
  2. 甲辰年正月初五迎财神

    2024-02-19 20:42:02       50 阅读
  3. 普中51单片机学习(七)

    2024-02-19 20:42:02       50 阅读
  4. 扫地机器人与项目管理

    2024-02-19 20:42:02       48 阅读
  5. 用结构体数组,完成宠物信息登记管理。

    2024-02-19 20:42:02       44 阅读
  6. 深度强化学习(DRL)算法 2 —— PPO 之 GAE 篇

    2024-02-19 20:42:02       50 阅读
  7. 文件的版本管理

    2024-02-19 20:42:02       57 阅读
  8. H3C- VRF/VPN-instance概念

    2024-02-19 20:42:02       43 阅读
  9. 洛谷P1019:[NOIP2000 提高组] 单词接龙

    2024-02-19 20:42:02       56 阅读