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

ba 复制代码
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中

ba 复制代码
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>

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

ba 复制代码
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
如果我们不想覆盖现有的值,我们可以使用

ba 复制代码
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 存在,这行代码将不会对散列表进行任何更改,但如果它不存在,它将创建一个类似于以下内容的键值对

ba 复制代码
{"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中的键值对

ba 复制代码
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中的键值对的数量:

ba 复制代码
println!("Size: {}", my_map.len());

Example 例如

ba 复制代码
use std::collections::HashMap;

fn main() {
    let text = "hello world hello rust world";

    // Create an empty hashmap to store word counts
    let mut word_count = HashMap::new();

    // Iterate over each word in the text
    for word in text.split_whitespace() {
        // Count the occurrences of each word
        let count = word_count.entry(word).or_insert(0);
        *count += 1;
    }

    // Print the word counts
    for (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.
    我们使用 HashMapentry 方法来获得单词的 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 :
该程序将输出:

ba 复制代码
hello: 2
world: 2
rust: 1
相关推荐
DreamByte18 分钟前
Python Tkinter小程序
开发语言·python·小程序
覆水难收呀26 分钟前
三、(JS)JS中常见的表单事件
开发语言·前端·javascript
阿华的代码王国30 分钟前
【JavaEE】多线程编程引入——认识Thread类
java·开发语言·数据结构·mysql·java-ee
繁依Fanyi36 分钟前
828 华为云征文|华为 Flexus 云服务器部署 RustDesk Server,打造自己的远程桌面服务器
运维·服务器·开发语言·人工智能·pytorch·华为·华为云
优思学院43 分钟前
优思学院|如何从零开始自己学习六西格玛?
大数据·运维·服务器·学习·六西格玛黑带·cssbb
weixin_486681141 小时前
C++系列-STL容器中统计算法count, count_if
开发语言·c++·算法
基德爆肝c语言1 小时前
C++入门
开发语言·c++
LN花开富贵1 小时前
stm32g431rbt6芯片中VREF+是什么?在电路中怎么设计?
笔记·stm32·单片机·嵌入式硬件·学习
怀九日1 小时前
C++(学习)2024.9.18
开发语言·c++·学习·面向对象·引用·
一道秘制的小菜1 小时前
C++第七节课 运算符重载
服务器·开发语言·c++·学习·算法