学习Rust第14天:HashMaps

今天我们来看看Rust中的hashmaps,在 std::collections crate中可用,是存储键值对的有效数据结构。本文介绍了创建、插入、访问、更新和迭代散列表等基本操作。通过一个计算单词出现次数的实际例子,我们展示了它们在现实世界中的实用性。Hashmaps提供了一种灵活而强大的组织和访问数据的方法,使其成为Rust编程中不可或缺的工具。

Introduction 介绍

Hashmaps store key value pairs and to use a hashing function to know where to put a key/value.
哈希映射存储键值对,并使用哈希函数来知道在哪里放置键/值。

Hashmaps are a part of the std::collections crate.
Hashmaps是 std::collections crate的一部分。

Creation 创作

Just like a vector or a string we can use the new() method for hashmaps.
就像向量或字符串一样,我们可以使用hashmaps的 new() 方法。

use std::collections::HashMap;fn main(){let mut my_map = HashMap::new();
}

Insertion 插入

we can insert key-value pairs into a hashmap using the insert method
我们可以使用 insert 方法将键值对插入到hashmap中

use std::collections::HashMap;fn main(){let mut my_map = HashMap::new();my_map.insert("key", "value");
}

Accessing 访问

We can access values in a hashmap using the get method, which returns an Option<&V>:
我们可以使用 get 方法访问hashmap中的值,该方法返回 Option<&V> :

use std::collections::HashMap;fn main(){let mut my_map = HashMap::new();my_map.insert("key", "value");if let Some(value) = my_map.get("key") {println!("Value: {}", value);} else {println!("Key not found");}}

Update 更新

We can update the value associated with a key using the insert method, which will replace the existing value if the key already exists:
我们可以使用 insert 方法更新与键关联的值,如果键已经存在,该方法将替换现有值:

use std::collections::HashMap;fn main(){let mut my_map = HashMap::new();my_map.insert("key", "value");if let Some(value) = my_map.get("key") {println!("Value: {}", value);} else {println!("Key not found");}my_map.insert("key", "new_value");
}

If we don’t want to overwrite existing values, we can use this
如果我们不想覆盖现有的值,我们可以使用

my_map.entry("key").or_insert("another_key_value_pair");

If key exists this line of code will not make any changes to the hashmap but if it does not exist it will create a key-value pair that looks something like this
如果 key 存在,这行代码将不会对散列表进行任何更改,但如果它不存在,它将创建一个类似于以下内容的键值对

{"key":"another_key_value_pair"}

The method entry gives us an entry enum which represents the value we provided in the brackets. Then we call the or_insert method which inserts a key-value pair if this already does not exist.
方法 entry 给了我们一个条目枚举,它表示我们在括号中提供的值。然后我们调用 or_insert 方法,如果键-值对不存在,则插入键-值对。

Iteration 迭代

We can iterate over the key-value pairs in a hashmap using a for loop or an iterator
我们可以使用 for 循环或迭代器遍历hashmap中的键值对

use std::collections::HashMap;fn main(){let mut my_map = HashMap::new();my_map.insert("key", "value");if let Some(value) = my_map.get("key") {println!("Value: {}", value);} else {println!("Key not found");}my_map.insert("key", "new_value");for (key, value) in &my_map {println!("Key: {}, Value: {}", key, value);}
}

Size 大小

We can get the number of key-value pairs in a hashmap using the len method:
我们可以使用 len 方法来获得hashmap中的键值对的数量:

println!("Size: {}", my_map.len());

Example 例如

use std::collections::HashMap;fn main() {let text = "hello world hello rust world";// Create an empty hashmap to store word countslet mut word_count = HashMap::new();// Iterate over each word in the textfor word in text.split_whitespace() {// Count the occurrences of each wordlet count = word_count.entry(word).or_insert(0);*count += 1;}// Print the word countsfor (word, count) in &word_count {println!("{}: {}", word, count);}
}
  • We import HashMap from the std::collections module to use hashmaps in our program.
    我们从 std::collections 模块导入 HashMap ,以便在程序中使用hashmaps。

In the main function: 在 main 函数中:

  • We define a string text containing the input text.
    我们定义一个包含输入文本的字符串 text 。
  • We create an empty hashmap named word_count to store the counts of each word.
    我们创建一个名为 word_count 的空散列表来存储每个单词的计数。
  • We iterate over each word in the input text using split_whitespace(), which splits the text into words based on whitespace.
    我们使用 split_whitespace() 来覆盖输入文本中的每个单词,它基于空格将文本拆分为单词。

For each word: 对于每个单词:

  • We use the entry method of the HashMap to get an Entry for the word. This method returns an enum Entry that represents a reference to a hashmap entry.
    我们使用 HashMap 的 entry 方法来获得单词的 Entry 。这个方法返回一个enum Entry ,它表示对hashmap条目的引用。
  • We use the or_insert method on the Entry to insert a new entry with a value of 0 if the word does not exist in the hashmap. Otherwise, it returns a mutable reference to the existing value.
    我们在 Entry 上使用 or_insert 方法来插入一个值为 0 的新条目,如果这个单词在hashmap中不存在的话。否则,它返回对现有值的可变引用。
  • We then increment the count of the word by dereferencing the mutable reference and using the += 1 operator.
    然后,我们通过解引用可变引用并使用 += 1 操作符来增加单词的计数。
  • After counting all the words, we iterate over the word_count hashmap using a for loop. For each key-value pair, we print the word and its count.
    在计算完所有单词后,我们使用 for 循环遍历 word_count hashmap。对于每个键值对,我们打印单词及其计数。

This program will output :
该程序将输出:

hello: 2
world: 2
rust: 1

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/644155.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

8、案例实战【处理百万级交易无压力】:支付系统JVM调优实战指南

8.1、前文回顾 本文将以一个日交易量达百万次的支付系统为背景,为大家深入分析在上线部署一个系统时,如何根据系统的业务量来合理设置JVM的堆内存大小。 通过阅读之前的文章,相信大家已经对编写的代码如何在JVM中运行的基本原理有了一定的了解,同时也知道如何通过参数来设…

本地部署Llama3教程,断网也能用啦!

4月18日&#xff0c;Meta在官方博客官宣了Llama3&#xff0c;标志着人工智能领域迈向了一个重要的飞跃。经过笔者的个人体验&#xff0c;Llama3 8B效果已经超越GPT-3.5&#xff0c;最为重要的是&#xff0c;Llama3是开源的&#xff0c;我们可以自己部署&#xff01; 本文和大家…

STM32点灯大师(点了一颗LED灯,轮询法)

配置操作&#xff1a; 一、使用CubeMX配置到大致的操作 1.1 选择芯片 1.2 选择引脚&#xff08;根据电路图&#xff09; 1.3 配置gpio口 1.4 配置系统 1.5文件项目操作 最后就是点击 二、点击CubeMX生成的代码&#xff0c;并且修改代码 2.1 看看效果 2.2 写代码

SpringBoot+Vue开发记录(三)

说明&#xff1a;本篇文章的主要内容为需求分析。需求分析这一部分很重要&#xff0c;也稍微有点子难搞&#xff0c;所以本篇文章里的有些内容会有失偏颇。 一、准备步骤 我打算做一个刷题项目&#xff0c;但是具体这个项目该怎么做&#xff0c;我是一头雾水。 所以就要先进行…

开源贡献代码之​探索一下Cython

探索一下Cython 本篇文章将会围绕最近给Apache提的一个feature为背景&#xff0c;展开讲讲Cython遇到的问题&#xff0c;以及尝试自己从0写一个库出来&#xff0c;代码也已经放星球了&#xff0c;感兴趣的同学可以去下载学习。 0.背景 最近在给apache arrow提的一个feature因为…

医院内可以导航吗?院内导航基于什么技术?

医院将就诊区域平面图、科室分布图&#xff0c;进行整合和数字化&#xff0c;最终形成一张与医院实际布局一致的电子地图&#xff0c;呈现在患者的手机上。基于这张电子地图&#xff0c;患者可以快速对自己的位置有一个清晰的认知&#xff0c;通过楼层切换、地图缩放&#xff0…

remote: HTTP Basic: Access deniedfatal: Authentication failed for

$ git push -u origin main remote: HTTP Basic: Access denied fatal: Authentication failed for https://gitcode.com/edenl/GD32E350_hid_keyboard.git/ 使用访问令牌做为密码登录即可。

新媒体运营-----短视频运营-----PR视频剪辑----软件基础

新媒体运营-----短视频运营-----PR视频剪辑-----持续更新(进不去说明我没写完)&#xff1a;https://blog.csdn.net/grd_java/article/details/138079659 文章目录 1.1 PR软件重置与初始化设置1.2 新建项目及序列设置1.3 PR工作区的管理方法1.4 导入4K超高清视频并与ME配合工作1…

目标检测算法使用体验是怎么样的?

一、YOLO的初次使用体验 1、基本概念 YOLO&#xff0c;全称为You Only Look Once&#xff0c;是一种实时目标检测算法。 YOLO的核心思想是将目标检测任务当作回归问题来解决&#xff0c;它可以在单次图像遍历中识别出图中的物体的类别和位置&#xff0c;因此得名“You Only …

DRF JWT认证基础

JWT认证 【1】base64使用 &#xff08;1&#xff09;使用场景 电子邮件附件&#xff1a;由于电子邮件协议只支持 ASCII 字符集&#xff0c;因此&#xff0c;如果要发送非 ASCII 数据&#xff08;如图片、音频、视频等&#xff09;&#xff0c;需要先将这些数据进行 base64 编…

Spring5深入浅出篇:JDK代理与CGLIB代理区别

Spring5深入浅出篇:JDK代理与CGLIB代理区别 很多粉丝私信我这个Spring5的课程在哪看,这边是在B站免费观看欢迎大家投币支持一下. https://www.bilibili.com/video/BV1hK411Y7zf JDK动态代理与CGLIB的区别 在Java的世界里&#xff0c;动态代理主要有两种实现方式&#xff1a;JDK…

【Python】基础知识(函数与数据容器)

笔者在C语言基础上学习python自用笔记 type() 返回数据类型 name "root" hei 1.8 wei 77 type_hei type(hei) type_wei type(wei) print(type(name)) print(type_hei) print(type_wei)在python中变量是没有类型的&#xff0c;它存储的数据是有类型的。 数据类…