学习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.mzph.cn/pingmian/3625.shtml

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

相关文章

故障诊断 | 基于迁移学习和SqueezeNet 的滚动轴承故障诊断(Matlab)

目录 效果一览基本介绍程序设计参考文献 效果一览 基本介绍 将一维轴承振动信号转换为二维尺度图&#xff08;时频谱图&#xff09;&#xff0c;并使用预训练网络应用迁移学习对轴承故障进行分类。 迁移学习显著减少了传统轴承诊断方法特征提取和特征选择所花费的时间&#xff…

Coursera: An Introduction to American Law 学习笔记 Week 02: Contract Law

An Introduction to American Law 本文是 https://www.coursera.org/programs/career-training-for-nevadans-k7yhc/learn/american-law 这门课的学习笔记。 文章目录 An Introduction to American LawInstructors Week 02: Contract LawKey Contract Law TermsSupplemental Re…

C语言笔试题之计数质数

计数质数 实例要求 给定整数 n &#xff0c;返回 所有小于非负整数 n 的质数的数量&#xff1b;示例&#xff1a; 实例分析 1、要计算小于非负整数 n 的质数的数量&#xff0c;可以使用埃拉托斯特尼筛法&#xff1b;2、这个算法通过标记素数的倍数来找出所有的素数&#x…

RTK负载(4K可见光+高分热成像+超广角+激光测距)四光AI智能识别跟踪吊舱技术详解

无人机光电吊舱的RTK负载&#xff08;4K可见光高分热成像超广角激光测距&#xff09;AI智能识别跟踪吊舱技术是一种高度集成和先进的无人机观测系统。系统结合了无人机的飞行能力和光电吊舱的多功能传感器&#xff0c;通过集成RTK&#xff08;实时动态差分定位&#xff09;技术…

STL_deque_stack_queue

Deque deque容器(双端队列) ​deque是一种双向开口的分段连续线性空间&#xff08;对外号称连续&#xff0c;使用者无法感知它是分段的&#xff09;。deque支持从头尾两端进行元素的插入和删除。deque没有容量的概念&#xff0c;因为它是动态地以分段连续空间组合而成的。随时…

python 脚本头(PyCharm+python头部信息、py头部信息、python头信息、py头信息、py文件头部)

文章目录 参考PyCharm设置脚本头头部信息 参考 https://developer.aliyun.com/article/1166544 https://blog.csdn.net/Dontla/article/details/131743495 https://blog.csdn.net/dongyouyuan/article/details/54408413 PyCharm设置脚本头 打开pycharm&#xff0c;点击file–…

【Harmony3.1/4.0】笔记六-对话框

概念 对话框在任何一款应用中&#xff0c;任何一个系统或者平台上使用都非常频繁&#xff0c;这里介绍一下鸿蒙系统中对话框的用法&#xff0c;分别为:普通文本对话框&#xff0c;自定义提示对话框&#xff0c;对话框菜单&#xff0c;警告提示对话框&#xff0c;列表选择对话框…

Unity 实现原神中的元素反应

一、元素反应 原神中共有七种元素&#xff0c;分别是水、火、冰、岩、风、雷、草。这七种元素能互相作用 Demo下载&#xff1a;Download 元素反应表格图示&#xff0c;可能不够精准 /火水雷冰草岩风绽放原激化火/蒸发超载融化燃烧结晶扩散烈绽放/水蒸发/感电冻结/碎冰绽放结晶…

Windows主机入侵检测与防御内核技术深入解析

第2章 模块防御的设计思想 2.1 执行与模块执行 本章内容为介绍模块执行防御。在此我将先介绍“执行”分类&#xff0c;以及“模块执行”在“执行”中的位置和重要性。 2.1.1 初次执行 恶意代码&#xff08;或者行为&#xff09;要在被攻击的机器上执行起来&#xff0c;看起…

Ubuntu 自己写的程序如何创建快捷方式

在Ubuntu中创建程序的快捷方式通常是通过将一个指向程序可执行文件的.desktop文件放入/usr/share/applications/或用户的~/.local/share/applications/目录来实现的。以下是创建快捷方式的基本步骤和示例&#xff1a; 在application里创建快捷方式 创建一个新的.desktop文件。…

【Linux】详解信号产生的方式

一、kill命令 在命令行中通过kill -数字 pid指令可以给指定进程发送指定信号。这里说明一下几个常见的信号&#xff1a; SIGINT&#xff08;2号信号&#xff09;&#xff1a;中断信号&#xff0c;通常由用户按下CtrlC产生&#xff0c;用于通知进程终止。SIGQUIT&#xff08;3号…

PG修改端口号与error: could not connect to server: could not connect to server 问题解决

刚开始学习PG修改端口号之后数据库端口号没变。 修改端口号&#xff1a;/usr/local/pgsql/data中的postgresql.conf中 修改后并不能直接生效需要重启PG&#xff1a; /usr/local/pgsql/bin/pg_ctl -D /usr/local/pgsql/data -l /usr/local/pgsql/data/logfile restart重启后新…

c++在visual studio上的默认配置

右键 新建项 右键源文件 属性

企业OA管理|基于SprinBoot+vue的企业OA管理系统(源码+数据库+文档)

企业OA管理目录 基于SprinBootvue的企业OA管理系统 一、前言 二、系统设计 三、系统功能设计 1 管理员模块的实现 1.1 用户信息管理 1.2 公告信息管理 1.3 客户关系管理 1.4 通讯录管理 2 用户模块的实现 2.1 客户关系添加 2.2 通讯录添加 2.3 日程安排添加 四、…

3.Docker常用镜像命令和容器命令详解

文章目录 1、Docker镜像命令1.1 获取镜像1.2 查看镜像1.2.1、images命令列出镜像1.2.2、tag命令添加镜像标签1.2.3、inspect命令查看详细信息1.2.4、history命令查看镜像历史 1.3 搜索镜像1.4 删除和清理镜像1.4.1、使用标签删除镜像1.4.2、清理镜像 1.5 创建镜像1.5.1、基于已…

Nginx 从入门到实践(1)

Nginx 从入门到实践 Nginx Nginx 从入门到实践Nginx介绍Nginx常用功能1、Http代理&#xff0c;反向代理2、负载均衡3、动静分离4、Nginx配置文件结构 简述Nginx和Apache的差异编译安装nginx服务在线安装nginxnginx 状态统计nginx 访问控制(用户校验、客户端授权)用户校验基于客…

【vue,unapi】UniApp引入全局js实现全局方法,全局变量

创建一个全局文件utils.js export const baseUrl "https://www.baidu.com/"export const fn () > {console.log("demo"); } export const obj {baseUrl : "https://www.baidu.com/",demo(){console.log("demo2");} }第一种&#…

4月25日 C++day4

#include <iostream> using namespace std;class Person {const string name;int age;char sex; public:Person():name("lisi"){cout << "Person无参构造" << endl;}Person(string name,int age,char sex):name(name),age(age),sex(sex)…

最新windows版本erlang26.0和rabbitmq3.13下载

Erlang下载 官网下载&#xff1a;https://www.erlang.org/patches/otp-26.0 百度网盘&#xff1a;https://pan.baidu.com/s/1xU4syn14Bh7QR-skjm_hOg 提取码&#xff1a;az1t RabbtitMQ下载 官网下载&#xff1a;https://www.rabbitmq.com/docs/install-windows 百度网盘…

Python二进制文件转换为文本文件

&#x1f47d;发现宝藏 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。【点击进入巨牛的人工智能学习网站】。 在日常编程中&#xff0c;我们经常会遇到需要将二进制文件转换为文本文件的情况。这可能是因…