• 学习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() 方法。

    1. use std::collections::HashMap;
    2. fn main(){
    3. let mut my_map = HashMap::new();
    4. }

    Insertion 插入

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

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

    Accessing 访问

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

    1. use std::collections::HashMap;
    2. fn main(){
    3. let mut my_map = HashMap::new();
    4. my_map.insert("key", "value");
    5. if let Some(value) = my_map.get("key") {
    6. println!("Value: {}", value);
    7. } else {
    8. println!("Key not found");
    9. }
    10. }

    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 方法更新与键关联的值,如果键已经存在,该方法将替换现有值:

    1. use std::collections::HashMap;
    2. fn main(){
    3. let mut my_map = HashMap::new();
    4. my_map.insert("key", "value");
    5. if let Some(value) = my_map.get("key") {
    6. println!("Value: {}", value);
    7. } else {
    8. println!("Key not found");
    9. }
    10. my_map.insert("key", "new_value");
    11. }

    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中的键值对

    1. use std::collections::HashMap;
    2. fn main(){
    3. let mut my_map = HashMap::new();
    4. my_map.insert("key", "value");
    5. if let Some(value) = my_map.get("key") {
    6. println!("Value: {}", value);
    7. } else {
    8. println!("Key not found");
    9. }
    10. my_map.insert("key", "new_value");
    11. for (key, value) in &my_map {
    12. println!("Key: {}, Value: {}", key, value);
    13. }
    14. }

    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 例如

    1. use std::collections::HashMap;
    2. fn main() {
    3. let text = "hello world hello rust world";
    4. // Create an empty hashmap to store word counts
    5. let mut word_count = HashMap::new();
    6. // Iterate over each word in the text
    7. for word in text.split_whitespace() {
    8. // Count the occurrences of each word
    9. let count = word_count.entry(word).or_insert(0);
    10. *count += 1;
    11. }
    12. // Print the word counts
    13. for (word, count) in &word_count {
    14. println!("{}: {}", word, count);
    15. }
    16. }
    • 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 :
    该程序将输出:

    1. hello: 2
    2. world: 2
    3. rust: 1
  • 相关阅读:
    使用gradio创建一个提取pdf、excel中表格数据的demo
    51单片机学习:DS1302时钟实验
    观察者模式在spring中的应用
    java实现课程表 II
    计算一个日期是一年中的第多天问题(普通、结构体版)
    目标检测算法改进系列之Backbone替换为RIFormer
    学习docker记录(三)
    1010 Radix
    【牛客刷题】带你在牛客刷题第八弹(简单排序)
    System Design现代系统设计概论
  • 原文地址:https://blog.csdn.net/yu101994/article/details/137555045