Rust HashMap

一、HashMap是什么,怎么用

1、HashMap是什么

HashMap 也是 Rust 标准库中提供的集合类型,但是又与动态数组不同,HashMap 中存储的是一一映射的 KV 键值对 ,并提供了平均时间复杂度为 O(1) 的查询方法

2、HashMap怎么用

(1)创建哈希表

使用new 方法创建

rust 复制代码
use std::collections::HashMap;//注意要导入包

// 创建一个HashMap,用于存储宝石种类和对应的数量
let mut my_gems = HashMap::new();

// 将宝石类型和对应的数量写入表中
my_gems.insert("红宝石", 1);
my_gems.insert("蓝宝石", 2);
my_gems.insert("河边捡的误以为是宝石的破石头", 18);

使用collection创建

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

    let teams_list = vec![
        ("中国队".to_string(), 100),
        ("美国队".to_string(), 10),
        ("日本队".to_string(), 50),
    ];

    let teams_map: HashMap<_,_> = teams_list.into_iter().collect();
    
    println!("{:?}",teams_map)
}

元组数据直接创建

rust 复制代码
use std::{collections::HashMap};
fn main() {
    let teams = [
        ("Chinese Team", 100),
        ("American Team", 10),
        ("France Team", 50),
    ];

    let mut teams_map1 = HashMap::new();
    for team in &teams {
        teams_map1.insert(team.0, team.1);
    }

    let teams_map2 = HashMap::from(teams);
    assert_eq!(teams_map1, teams_map2);

    println!("Success!")
}

(2)哈希表的元素所有权转移

即放入元素到哈希表中也会发生所有权转移

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

    let name = String::from("Sunface");
    let age = 18;

    let mut handsome_boys = HashMap::new();
    handsome_boys.insert(name, age);

    println!("因为过于无耻,{}已经被从帅气男孩名单中除名", name);
    println!("还有,他的真实年龄远远不止{}岁", age);
}

(3) 获取哈希表中的元素

rust 复制代码
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: Option<&i32> = scores.get(&team_name);
  1. get 方法返回一个 Option<&i32> 类型:当查询不到时,会返回一个 None,查询到时返回 Some(&i32)
  2. &i32是对 HashMap 中值的借用,如果不使用借用,可能会发生所有权的转移

(4)遍历哈希表中的元素

rust 复制代码
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);
}

(5)哈希表插入新值

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

    let mut scores = HashMap::new();

    scores.insert("Blue", 10);
}

(6)没有则插入

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

    let mut scores = HashMap::new();

    scores.insert("Blue", 10);
    // 查询Yellow对应的值,若不存在则插入新值
    let v = scores.entry("Yellow").or_insert(5);
    assert_eq!(*v, 5); // 不存在,插入5
}

(7)已有则更新

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

    let mut scores = HashMap::new();

    scores.insert("Blue", 10);

    // 覆盖已有的值
    let old = scores.insert("Blue", 20);//覆盖
    assert_eq!(old, Some(10));
    
}
相关推荐
听风吟丶44 分钟前
Java 8 Stream API 高级实战:从数据处理到性能优化的深度解析
开发语言·python
q***46521 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
hygge9991 小时前
Spring Boot + MyBatis 整合与 MyBatis 原理全解析
java·开发语言·经验分享·spring boot·后端·mybatis
q***13611 小时前
十七:Spring Boot依赖 (2)-- spring-boot-starter-web 依赖详解
前端·spring boot·后端
q***25211 小时前
Spring Boot接收参数的19种方式
java·spring boot·后端
WX-bisheyuange1 小时前
基于Spring Boot的民谣网站的设计与实现
java·spring boot·后端
q***14641 小时前
Spring Boot文件上传
java·spring boot·后端
Run_Teenage2 小时前
C++:智能指针的使用及其原理
开发语言·c++·算法
WX-bisheyuange3 小时前
基于Spring Boot的民宿预定系统的设计与实现
java·spring boot·后端·毕业设计
码界奇点4 小时前
Java设计模式精讲从基础到实战的常见模式解析
java·开发语言·设计模式·java-ee·软件工程