学习Rust第14天:HashMaps

news/2024/5/20 9:21:43

今天我们来看看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.mrgr.cn/p/73623362

相关文章

基于harris角点和RANSAC算法的图像拼接matlab仿真

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 5.算法完整程序工程 1.算法运行效果图预览 2.算法运行软件版本 MATLAB2022a 3.部分核心程序 ....................................................................... I1_harris fu…

对EKS(AWS云k8s)启用AMP(AWS云Prometheus)监控+AMG(AWS云 grafana)

问题 需要在针对已有的EKS k8s集群启用Prometheus指标监控。而且&#xff0c;这里使用AMP即AWS云的Prometheus托管服务。好像这个服务&#xff0c;只有AWS国际云才有&#xff0c;AWS中国云没得这个托管服务。下面&#xff0c;我们就来尝试在已有的EKS集群上面启用AMP监控。 步…

IP地址定位:揭秘精准定位的技术与应用

在数字化时代&#xff0c;IP地址已成为连接互联网世界的关键标识之一。但是&#xff0c;很多人对于IP地址的精准定位能力存在疑虑。本文将深入探讨IP地址定位的技术原理以及其在实际应用中的精确度。 IP地址查询&#xff1a;IP数据云 - 免费IP地址查询 - 全球IP地址定位平台 …

运行游戏提示dll文件丢失,分享多种有效的解决方法

在我们日常频繁地利用电脑进行娱乐活动&#xff0c;特别是畅玩各类精彩纷呈的电子游戏时&#xff0c;常常会遭遇一个令人困扰的问题。当我们满怀期待地双击图标启动心仪的游戏程序&#xff0c;准备全身心投入虚拟世界时&#xff0c;屏幕上却赫然弹出一条醒目的错误提示信息&…

xgp加速器免费 微软商店xgp用什么加速器

2001年11月14日深夜&#xff0c;比尔盖茨亲自来到时代广场&#xff0c;在午夜时分将第一台Xbox交给了来自新泽西的20岁年轻人爱德华格拉克曼&#xff0c;后者在回忆中说&#xff1a;“比尔盖茨就是上帝。”性能超越顶级PC的Xbox让他们趋之若鹜。2000年3月10日&#xff0c;微软宣…

链游:未来游戏发展的新风向

链游&#xff0c;即区块链游戏的一种&#xff0c;是一种将区块链技术与游戏玩法相结合的创新型游戏。它利用区块链技术的特性&#xff0c;如去中心化、可追溯性和安全性&#xff0c;为玩家提供了一种全新的游戏体验。链游通常采用智能合约来实现游戏的规则和交易系统&#xff0…

Oracle delete删除数据是否为逻辑删除、新插入数据占用的数据块位置实验

假设一&#xff1a;数据库delete删除为直接删除 假设二&#xff1a;数据库delete删除为逻辑删除&#xff0c;在数据块标记出来&#xff0c;但是实际并没有删除。 方式一&#xff1a;通过dump数据块的方式来实现 我们先用小数据量&#xff0c;通过dump数据块的方式来实现 -- 数…

图搜索算法详解:广度优先搜索与深度优先搜索的探索之旅

图搜索算法详解&#xff1a;广度优先搜索与深度优先搜索的探索之旅 1. 广度优先搜索&#xff08;BFS&#xff09;1.1 伪代码1.2 C语言实现 2. 深度优先搜索&#xff08;DFS&#xff09;2.1 伪代码2.2 C语言实现 3. 总结 图搜索算法是计算机科学中用于在图结构中查找路径的算法。…

Python打怪升级(4)

在计算机领域常常有说"合法"和"非法"指的是:是否合理&#xff0c;是否有效&#xff0c;并不是指触犯了法律。 random.randint(begin,end) 详细讲解一下这个random是指模板&#xff0c;也就是别人写好的代码直接来用&#xff0c;在Python当中&#xff0c;…

接口测试和Mock学习路线(上)

一、接口测试和Mock学习路线-第一阶段&#xff1a; 掌握接口测试的知识体系与学习路线掌握面试常见知识点之 HTTP 协议掌握常用接口测试工具 Postman掌握常用抓包工具 Charles 与 Fiddler结合知名产品实现 mock 测试与接口测试实战练习 1.接口协议&#xff1a; 需要先了解 O…

探秘MySQL主从复制的多种实现方式

欢迎来到我的博客&#xff0c;代码的世界里&#xff0c;每一行都是一个故事 探秘MySQL主从复制的多种实现方式 前言基于语句的复制原理实现方法应用场景及优缺点应用场景优点缺点 基于行的复制原理实现方法优势和适用性优势适用性 基于混合模式的复制混合模式复制的工作原理混合…

数值分析复习:Richardson外推和Romberg算法

文章目录 Richardson外推Romberg&#xff08;龙贝格&#xff09;算法 本篇文章适合个人复习翻阅&#xff0c;不建议新手入门使用 本专栏&#xff1a;数值分析复习 的前置知识主要有&#xff1a;数学分析、高等代数、泛函分析 本节继续考虑数值积分问题 Richardson外推 命题&a…

WindowsPE重装Windows系统详细介绍

本文详细介绍了WindowsPE、UEFI BIOS、如何制作WindowsPE、网络唤醒WOL、如何格式化硬盘及分区 、GHost还原数据、驱动程序分类相关知识目录目录理论知识 什么是WindowsPE? 什么是UEFI BIOS?(简)实操 如何制作WindowsPE? 如何进入BIOS? 常用项介绍 设置U盘启动 网络…

02_c/c++开源库ZeroMQ

1.安装 C库 libzmq sudo apt install libzmq3-dev 实例: https://zeromq.org/get-started/?languagec&librarylibzmq# 编译依赖: pkg-config --cflags --libs libzmq or cat /usr/lib/x86_64-linux-gnu/pkgconfig/libzmq.pc -isystem /usr/include/mit-krb5 -I/usr/in…

dwc3控制器是怎么处理otg

概念 在OTG中&#xff0c;初始主机设备称为A设备&#xff0c;外设称为B设备。可用电缆的连接方式来决定初始角色。两用设备使用新型Mini-AB插座&#xff0c;从而使Mini-A插头、Mini-B插头和Mini-AB插座增添了第5个引脚&#xff08;ID&#xff09;&#xff0c;以用于识别不同的…

存储器数据恢复相关知识

讲述硬盘基本结构及其储存理论,介绍如何恢复常用存储器数据。目录目录理论知识 硬盘如何储存数据? 磁道和扇区简介 盘面号 磁道 柱面 扇区 硬盘如何读写数据? 数据删除原理 数据如何丢失的? 人为原因造成的数据丢失: 自然灾害造成的数据丢失: 软件原因造成…

ARM学习(26)链接库的依赖查看

笔者今天来聊一下查看链接库的依赖。 通常情况下&#xff0c;运行一个可执行文件的时候&#xff0c;可能会出现找不到依赖库的情况&#xff0c;比如图下这种情况&#xff0c;可以看到是缺少了license.dll或者libtest.so&#xff0c;所以无法运行。怎么知道它到底缺少什么dll呢&…

构建RAG应用-day05: 如何评估 LLM 应用 评估并优化生成部分 评估并优化检索部分

评估 LLM 应用 1.一般评估思路 首先,你会在一到三个样本的小样本中调整 Prompt ,尝试使其在这些样本上起效。 随后,当你对系统进行进一步测试时,可能会遇到一些棘手的例子,这些例子无法通过 Prompt 或者算法解决。 最终,你会将足够多的这些例子添加到你逐步扩大的开发集中…

android脱壳第二发:grpc-dumpdex加修复

上一篇我写的dex脱壳&#xff0c;写到银行类型的app的dex修复问题&#xff0c;因为dex中被抽取出来的函数的code_item_off 的偏移所在的内存&#xff0c;不在dex文件范围内&#xff0c;所以需要进行一定的修复&#xff0c;然后就停止了。本来不打算接着搞得&#xff0c;但是写了…

ELK 日志分析系统(二)

一、ELK Kibana 部署 1.1 安装Kibana软件包 #上传软件包 kibana-5.5.1-x86_64.rpm 到/opt目录 cd /opt rpm -ivh kibana-5.5.1-x86_64.rpm 1.2 设置 Kibana 的主配置文件 vim /etc/kibana/kibana.yml --2--取消注释&#xff0c;Kiabana 服务的默认监听端口为5601 server.po…