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));
    
}
相关推荐
fs哆哆3 小时前
在VB.net中一维数组,与VBA有什么区别
java·开发语言·数据结构·算法·.net
蝎子莱莱爱打怪4 小时前
Hadoop3.3.5、Hbase2.6.1 集群搭建&Phoenix使用记录
大数据·后端·hbase
johnZhangqi4 小时前
深圳大学-计算机信息管理课程实验 C++ 自考模拟题
java·开发语言·c++
David爱编程4 小时前
并发编程三大特性全解析:原子性、可见性、有序性,一文讲透!
java·后端
Sally璐璐4 小时前
Go语言变量声明与初始化详解
java·开发语言·golang
luofeiju4 小时前
交叉编译笔记
开发语言
StudyWinter5 小时前
【C++】仿函数和回调函数
开发语言·c++·回调函数·仿函数
你的人类朋友5 小时前
git常见操作整理(持续更新)
前端·git·后端
你的人类朋友5 小时前
git中的Fast-Forward是什么?
前端·git·后端
C4程序员5 小时前
北京JAVA基础面试30天打卡14
java·开发语言·面试