Rust 集合类型之HashMap

概述

哈希map(hash map)是一种基于哈希表的集合类型,用于存储键值对。提供了快速的查找,插入和删除的操作。

HashMap<k, v>类型存储了一个键类型K对应一个值类型V的映射。

创建一个哈希map

在Rust中,使用标准库中的HashMap来实现哈希表。需要在代码中引入std::collections::HashMap模块。

//记录两支队伍的分数,分别是蓝队和黄队。蓝队有10分,黄队有50分
use std::collectons::HashMap;

let mut scores = HashMap::new(); //创建一个空的HashMap

scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);

访问哈希map中的值

通过get方法并提供对应的键来从哈希map中获取值。

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

遍历哈希map的键值对

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

更新哈希map

//覆盖一个值

use std::collections::HashMap;

let mut scores = HashMap::new();

scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25); //原始的值被25覆盖了

println!("{:?}", scores);

只有键灭有对应值时插入键值对

当检查某个特定的键是否已经存在于哈希map中并进行如下操作:如果哈希map中键已经存在则不做任何操作,如果不存在则连同值一块插入。

use std::collections::HashMap;

let mut scores = HashMap::new();
scores.insert(String::from("Blue"), 10);

scores.entry(String::from("Yellow")).or_insert(50);
scores.entry(String::from("Blue").or_insert(50);

println!("{:?}", scores);

//输出结果:
  {"Yellow": 50, "Blue": 10}

第一个entry调用会插入黄队和值50,因为没有黄队和值。第二个entry调用不会改变哈希map,因为蓝队已经有了值10。

根据旧值更新一个值

use std::collections::HashMap;

let text = "hello world wonderful world";

let mut map = HashMap::new();

for word in text.split_whitespace() {
    let count = map.entry(word).or_insert(0);
    *count +=1;
}

println!("{:?}", map);

//输出结果:
  {"world":2, "hello":1, "wonderful":1}

split_whitespace方法返回一个由空格分隔text值子slice的迭代器。

or_insert方法返回这个键的值的一个可变引用(&mut V)。我们将这个可变引用储存在count变量中,所以为了赋值必须首先使用星号 (*) 解引用count。

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值