当前位置: 首页 > news >正文

Rust语言之哈希表

文章目录

  • 哈希表(Hash map)
    • 一、新建哈希表
    • 二、访问某个元素
      • 索引访问
      • GET方法
    • 二、插入新元素
    • 三、遍历哈希表
    • 四、检查某个元素是否存在
      • contains_key方法
      • entry方法
    • 五、元素更新
      • 使用contains_key+insert 的方法
      • 使用entry方法
  • 六、删除元素


Rus设计语言官方教程

哈希表(Hash map)

哈希表也是集合中的一种,也是最常用的集合形式,目前Rust语言核心部分没有对哈希表进行实现,是使用标准库提供的。

一、新建哈希表

fn main() {  use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.insert(String::from("Yellow"), 50);println!("{:?}",scores); //{"Yellow": 50, "Blue": 10}
}

二、访问某个元素

索引访问

fn main() {  use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.insert(String::from("Yellow"), 50);println!("value: {}",scores["Blue"]); // 10
}

GET方法

官方教程上的方法

fn main() {  use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.insert(String::from("Yellow"), 50);let team_name = String::from("Blue");let score = scores.get(&team_name).copied().unwrap_or(0);println!("value: {}",score); // 10
}

以上两种方法都必须保证访问的元素存在,否则会报错

二、插入新元素

fn main() {  use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.insert(String::from("Yellow"), 50);println!("{:?}",scores); //{"Yellow": 50, "Blue": 10}scores.insert(String::from("Red"), 100);println!("{:?}",scores);// {"Red": 100, "Yellow": 50, "Blue": 10}
}

这里可以看出,哈希表中的元素是没有顺序的

三、遍历哈希表

fn main() {  use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.insert(String::from("Yellow"), 50);for (key, value) in &scores {println!("{key}: {value}");}
}=>
Yellow: 50
Blue: 10

四、检查某个元素是否存在

Rust语言中检查哈希表元素是否存在,有两种方法,contains_key方法和entry

  • contains_key方法用于检查HashMap中是否包含特定的键。它返回一个布尔值,指示键是否存在。
  • entry方法用于高效地处理键值对的插入和更新,它返回一个Entry枚举,可以是Occupied(键已存在)或Vacant(键不存在)。

contains_key方法

fn main() {  use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.insert(String::from("Yellow"), 50);if scores.contains_key("Red"){println!("value :{}",scores["Red"]);}else {println!("Red is not found")}
}=>Red is not found

entry方法

entry方法多用于对值的更新,eor_insert方法在键对应的值存在时就返回这个值的可变引用,如果不存在则将参数作为新值插入并返回新值的可变引用

fn main() {  use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.insert(String::from("Yellow"), 50);scores.entry(String::from("Red")).or_insert(100);scores.entry(String::from("Blue")).or_insert(50);println!("{:?}", scores);//{"Blue": 10, "Red": 100, "Yellow": 50}
}

五、元素更新

使用contains_key+insert 的方法

fn main() {  use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.insert(String::from("Yellow"), 50);let team_list =["Blue","Red"];for i in team_list{if scores.contains_key(i){scores.insert(i.to_string(), scores[i]+50);}else{scores.insert(i.to_string(), 50);}}println!("{:?}",scores);//{"Red": 50, "Blue": 60, "Yellow": 50}
}

使用entry方法

fn main() {  use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.insert(String::from("Yellow"), 50);let team_list =["Blue","Red"];for i in team_list{let count = scores.entry(i.to_string()).or_insert(0);*count += 50;}println!("{:?}",scores);//{"Red": 50, "Blue": 60, "Yellow": 50}
}

相比使用contains_key+insert 的方法,这种方法更优雅。

六、删除元素

fn main() {  use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.insert(String::from("Yellow"), 50);scores.insert(String::from("Red"), 80);println!("{:?}",scores);//{"Blue": 10, "Yellow": 50, "Red": 80}scores.remove("Red");println!("{:?}",scores);//{"Blue": 10, "Yellow": 50}
}

相关文章:

  • Gitlab和Jenkins集成 实现CI (二)
  • 机器学习系列——(十四)正则化回归
  • Java多线程编程中的异常处理策略
  • C语言如何输⼊字符数组?
  • 嵌入式Qt Qt 中的坐标系统
  • 代码随想录算法——数组
  • 【UE 游戏编程基础知识】
  • element-ui解决上传文件时需要携带请求数据的问题
  • 用Python来实现2024年春晚刘谦魔术
  • 操作系统面试问题——说一下什么是零拷贝?
  • 蓝桥杯刷题--python-4
  • 域名解析大概过程笔记
  • Dubbo集成Zookeeper embbed模式
  • 屏幕字体种类介绍
  • 第62讲商品搜索动态实现以及性能优化
  • JS中 map, filter, some, every, forEach, for in, for of 用法总结
  • [译] 理解数组在 PHP 内部的实现(给PHP开发者的PHP源码-第四部分)
  • 《Javascript数据结构和算法》笔记-「字典和散列表」
  • 《深入 React 技术栈》
  • Android Volley源码解析
  • JavaScript 一些 DOM 的知识点
  • Js实现点击查看全文(类似今日头条、知乎日报效果)
  • JS正则表达式精简教程(JavaScript RegExp 对象)
  • Linux Process Manage
  • python 装饰器(一)
  • python3 使用 asyncio 代替线程
  • socket.io+express实现聊天室的思考(三)
  • Terraform入门 - 1. 安装Terraform
  • Transformer-XL: Unleashing the Potential of Attention Models
  • 百度地图API标注+时间轴组件
  • 测试如何在敏捷团队中工作?
  • 从tcpdump抓包看TCP/IP协议
  • 反思总结然后整装待发
  • 规范化安全开发 KOA 手脚架
  • 聊聊directory traversal attack
  • 算法之不定期更新(一)(2018-04-12)
  • 微信端页面使用-webkit-box和绝对定位时,元素上移的问题
  • 微信小程序--------语音识别(前端自己也能玩)
  • 我是如何设计 Upload 上传组件的
  • 我这样减少了26.5M Java内存!
  • 一起来学SpringBoot | 第三篇:SpringBoot日志配置
  • 国内开源镜像站点
  • ​DB-Engines 12月数据库排名: PostgreSQL有望获得「2020年度数据库」荣誉?
  • ###项目技术发展史
  • #快捷键# 大学四年我常用的软件快捷键大全,教你成为电脑高手!!
  • #我与Java虚拟机的故事#连载18:JAVA成长之路
  • $(document).ready(function(){}), $().ready(function(){})和$(function(){})三者区别
  • %check_box% in rails :coditions={:has_many , :through}
  • (十) 初识 Docker file
  • (十二)springboot实战——SSE服务推送事件案例实现
  • .NET CF命令行调试器MDbg入门(四) Attaching to Processes
  • .NET CF命令行调试器MDbg入门(一)
  • .net 程序发生了一个不可捕获的异常
  • .net 无限分类
  • .NET 依赖注入和配置系统