Rust常用数据结构教程 Map
文章目录
- 一、Map类型
- 1.HashMap
- hashMap的简单插入
- entry().or_insert()更新hashMap
- 2.什么时候用HashMap
- 3.HashMap中的键
- 二、BTreeMap
- 1.什么时候用BTreeMap
- 2.BTreeMap中的键
- 参考
一、Map类型
·键值对数据又称字典数据类型
·主要有两种
- · HashMap
·- BTreeMap
1.HashMap
·HashMap<K,V>类型储存了一个键类型K对应一个值类型V的映射。它通过一个 哈希函数(hashing function)来实现映射,决定如何将键和值放入内存中。
·HashMap的数据和Vec一样在heap上
hashMap的简单插入
#![allow(unused)]
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);}
}
cargo runCompiling abc v0.1.0 (/home/wangji/installer/rust/bobo/abc)Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.91sRunning `target/debug/abc`
Yellow: 50
Blue: 10
entry().or_insert()更新hashMap
直接覆盖
#![allow(unused)]
fn main() {
use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Blue"), 25);println!("{:?}", scores);
}
or_insert在没有key的情况下才插入
#![allow(unused)]
fn main() {use std::collections::HashMap;let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.entry(String::from("Yellow")).or_insert(50);scores.entry(String::from("Blue")).or_insert(50);println!("{:?}", scores);
}
cargo runBlocking waiting for file lock on package cacheBlocking waiting for file lock on package cacheCompiling abc v0.1.0 (/home/wangji/installer/rust/bobo/abc)Finished `dev` profile [unoptimized + debuginfo] target(s) in 13.96sRunning `target/debug/abc`
{"Blue": 10, "Yellow": 50}
or_inser根据旧值更新一个值,会返回插入的pair的value的引用
#![allow(unused)]
fn main() {use std::collections::HashMap;let text = "hello world wonderful world";let mut map = HashMap::new();for word in text.split_whitespace() {let count = map.entry(word).or_insert(0);*count += 1;}println!("{:?}", map);
}
cargo runFinished `dev` profile [unoptimized + debuginfo] target(s) in 0.00sRunning `target/debug/abc`
{"hello": 1, "wonderful": 1, "world": 2}
2.什么时候用HashMap
·仅次于Vec的常用数据类型
·存储数据为键值对类型
需要查找的速度
- in-memory cache
3.HashMap中的键
·因为要满足哈希函数,所以HashMap对键有特殊要求
·实现Hash、Eq、PartialEq
·一般结构体: #[derive(Debug, PartialEq, Hash, Eq)]
use std::collections::HashMap;// Hash Eq PartialEq
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Car {id: i32,price: i32,
}fn main() {let _int_map: HashMap<i32, i32> = HashMap::new();let _int_map: HashMap<i32, i32> = HashMap::with_capacity(10);// 通过数组来创建maplet mut car_map = HashMap::from([("Car1",Car {id: 1,price: 10000,},),("Car2", Car { id: 2, price: 4000 }),("Car3",Car {id: 3,price: 890000,},),]);// 打印实际是无序的for (k, v) in &car_map {println!("{k}:{:?}", v);}// getprintln!("Some {:?}", car_map.get("Car1"));println!("None {:?}", car_map.get("Car6"));// 覆盖性插入insertcar_map.insert("Car4",Car {id: 4,price: 80000,},);println!("{:?}", car_map);car_map.insert("Car4",Car {id: 5,price: 300000,},);println!("{:?}", car_map);// 只在键没有时插入// Entrycar_map.entry("Car4").or_insert(Car { id: 9, price: 9000 });println!("{:?}", car_map);// removecar_map.remove("Car4");println!("{:?}", car_map);car_map.entry("Car4").or_insert(Car { id: 9, price: 9000 });println!("{:?}", car_map);// 加上注释PartialEq, Eq, Hashlet mut car_map = HashMap::from([(Car {id: 1,price: 10000,},"Car1",),(Car { id: 2, price: 4000 }, "Car2"),(Car {id: 3,price: 890000,},"Car3",),]);println!("Car2: {:?}\n",car_map.get(&Car {id: 1,price: 10000}));for (car, name) in &car_map {println!("{:?}: {name}", car)}// Filter:会原地修改mapcar_map.retain(|c, _| c.price < 5000);println!("< 4000 {:?}", car_map);
}
编译及运行
cargo runBlocking waiting for file lock on build directoryCompiling data_struct v0.1.0 (/home/wangji/installer/rust/data_struct/data_struct)Finished `dev` profile [unoptimized + debuginfo] target(s) in 13.52sRunning `target/debug/data_struct`
Car1:Car { id: 1, price: 10000 }
Car3:Car { id: 3, price: 890000 }
Car2:Car { id: 2, price: 4000 }
Some Some(Car { id: 1, price: 10000 })
None None
{"Car4": Car { id: 4, price: 80000 }, "Car2": Car { id: 2, price: 4000 }, "Car1": Car { id: 1, price: 10000 }, "Car3": Car { id: 3, price: 890000 }}
{"Car4": Car { id: 5, price: 300000 }, "Car2": Car { id: 2, price: 4000 }, "Car1": Car { id: 1, price: 10000 }, "Car3": Car { id: 3, price: 890000 }}
{"Car4": Car { id: 5, price: 300000 }, "Car2": Car { id: 2, price: 4000 }, "Car1": Car { id: 1, price: 10000 }, "Car3": Car { id: 3, price: 890000 }}
{"Car2": Car { id: 2, price: 4000 }, "Car1": Car { id: 1, price: 10000 }, "Car3": Car { id: 3, price: 890000 }}
{"Car4": Car { id: 9, price: 9000 }, "Car2": Car { id: 2, price: 4000 }, "Car1": Car { id: 1, price: 10000 }, "Car3": Car { id: 3, price: 890000 }}
Car2: Some("Car1")Car { id: 3, price: 890000 }: Car3
Car { id: 1, price: 10000 }: Car1
Car { id: 2, price: 4000 }: Car2
< 4000 {Car { id: 2, price: 4000 }: "Car2"}
二、BTreeMap
map的有序形式
内部基于BTree创建
1.什么时候用BTreeMap
·当你需要有序map时
·当你查找时,有序可以提供你的性能 (比如二分查找法)
·注意:有序是有代价的
·BTreeMap缓存效率和搜索中进行了折衷
2.BTreeMap中的键
·因为需要对键值排序所以需要Key实现
- Ord
- PartialOrd
use std::collections::BTreeMap;// Hash Eq PartialEq
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct Car {id: i32,price: i32,
}impl Ord for Car {fn cmp(&self, other: &Self) -> std::cmp::Ordering {self.price.cmp(&other.price)}
}impl PartialOrd for Car {fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {Some(self.price.cmp(&other.price))}
}fn main() {let _int_map: BTreeMap<i32, i32> = BTreeMap::new();// let _int_map:BTreeMap<i32, i32> = BTreeMap::with_capacity(10);// 通过数组来创建maplet mut car_map = BTreeMap::from([("Car1",Car {id: 1,price: 10000,},),("Car2", Car { id: 2, price: 4000 }),("Car3",Car {id: 3,price: 890000,},),]);println!("{:#?}", car_map);println!("------------------------");let mut car_map = BTreeMap::from([(Car {id: 1,price: 10000,},1,),(Car { id: 2, price: 4000 }, 2),(Car {id: 3,price: 890000,},3,),]);for (k, v) in &car_map {println!("{:?}: {v}", k);}println!("----------------------");car_map.insert(Car {id: 4,price: 90000,},4,);for (k, v) in &car_map {println!("{:?}: {v}", k);}println!("----------------------");println!("{:?}",car_map.get(&Car {id: 1,price: 10000}));println!("{:?}", car_map.first_key_value());println!("{:?}", car_map.last_key_value());println!("----------------------");// removelet car = car_map.pop_first().unwrap();println!("{:?}", car);let car = car_map.pop_last().unwrap();println!("{:?}", car);println!("----------------------");for (k, v) in &car_map {println!("{:?}: {v}", k);}println!("----------------------");// remove(index)不建议你用car_map.remove(&Car {id: 1,price: 10000,});for (k, v) in &car_map {println!("{:?}: {v}", k);}println!("----------------------");car_map.clear();println!("{}", car_map.is_empty());
}
编译及运行
cargo runCompiling data_struct v0.1.0 (/home/wangji/installer/rust/data_struct/data_struct)
warning: variable does not need to be mutable--> src/main.rs:27:9|
27 | let mut car_map = BTreeMap::from([| ----^^^^^^^| || help: remove this `mut`|= note: `#[warn(unused_mut)]` on by defaultwarning: `data_struct` (bin "data_struct") generated 1 warning (run `cargo fix --bin "data_struct"` to apply 1 suggestion)Finished `dev` profile [unoptimized + debuginfo] target(s) in 6.51sRunning `target/debug/data_struct`
{"Car1": Car {id: 1,price: 10000,},"Car2": Car {id: 2,price: 4000,},"Car3": Car {id: 3,price: 890000,},
}
------------------------
Car { id: 2, price: 4000 }: 2
Car { id: 1, price: 10000 }: 1
Car { id: 3, price: 890000 }: 3
----------------------
Car { id: 2, price: 4000 }: 2
Car { id: 1, price: 10000 }: 1
Car { id: 4, price: 90000 }: 4
Car { id: 3, price: 890000 }: 3
----------------------
Some(1)
Some((Car { id: 2, price: 4000 }, 2))
Some((Car { id: 3, price: 890000 }, 3))
----------------------
(Car { id: 2, price: 4000 }, 2)
(Car { id: 3, price: 890000 }, 3)
----------------------
Car { id: 1, price: 10000 }: 1
Car { id: 4, price: 90000 }: 4
----------------------
Car { id: 4, price: 90000 }: 4
----------------------
true
参考
- Rust常用数据结构教程
相关文章:
Rust常用数据结构教程 Map
文章目录 一、Map类型1.HashMaphashMap的简单插入entry().or_insert()更新hashMap 2.什么时候用HashMap3.HashMap中的键 二、BTreeMap1.什么时候用BTreeMap2.BTreeMap中的键 参考 一、Map类型 键值对数据又称字典数据类型 主要有两种 HashMap - BTreeMap 1.HashMap HashM…...
<el-popover>可以展示select change改变值的时候popover 框会自动隐藏
一、问题定位 点击查看详细链接 element-plus 的 popover 组件,依赖 tooltip 组件;当 tooltip 的 trigger 的值不是 hover 时,会触发 close 事件;下拉框的 click 事件,触发了 tooltip 组件的 close 事件 总结一下&am…...

SQLI LABS | Less-37 POST-Bypass mysql_real_escape_string
关注这个靶场的其它相关笔记:SQLI LABS —— 靶场笔记合集-CSDN博客 0x01:过关流程 输入下面的链接进入靶场(如果你的地址和我不一样,按照你本地的环境来): http://localhost/sqli-labs/Less-37/ 是一个登…...

数字后端零基础入门系列 | Innovus零基础LAB学习Day9
Module 16 Wire Editing 这个章节的学习目标是学习如何在innovus中手工画线,切断一根线,换孔,更改一条net shape的layer和width等等。这个技能是每个数字IC后端工程师必须具备的。因为项目后期都需要这些技能来修复DRC和做一些手工custom走线…...
深度学习:GLUE(General Language Understanding Evaluation)详解
GLUE(General Language Understanding Evaluation)详解 GLUE(General Language Understanding Evaluation)是一个用于评估和比较自然语言理解(NLU)系统的综合基准测试。它包括了一系列的任务,旨…...

基于Multisim直流稳压电源电路±9V、±5V(含仿真和报告)
【全套资料.zip】直流稳压电源电路9V、5VMultisim仿真设计数字电子技术 文章目录 功能一、Multisim仿真源文件二、原理文档报告资料下载【Multisim仿真报告讲解视频.zip】 功能 一般直流稳压电源都使用220伏市电作为电源,经过变压、整流、滤波后给稳压电路进行稳压…...
Vue Cli的配置中configureWebpack和chainWebpack的主要作用及区别是什么?
直接区别: configureWebpack项直接覆盖同名配置;chainWebpack项直接修改默认配置。 configureWebpack配置: // vue.config.js module.exports {configureWebpack: {plugins: [new MyAwesomeWebpackPlugin()]} }该代码段中的对象将会被web…...
ubuntu主机搭建sysroot交叉编译环境
ubuntu主机搭建sysroot交叉编译环境 主机是 ubuntu22.04 x86-64 hostubuntu22.04host-archx86-64host-cpui9-13900k 目标板是香橙派5b ,ubuntu22.04,aarch64 ,cpu rk3588s targetubuntu22.04target-archaarch64target-cpurk3588s 安装 qemu-user-static 进入 …...

Python注意力机制Attention下CNN-LSTM-ARIMA混合模型预测中国银行股票价格|附数据代码...
全文链接:https://tecdat.cn/?p38195 股票市场在经济发展中占据重要地位。由于股票的高回报特性,股票市场吸引了越来越多机构和投资者的关注。然而,由于股票市场的复杂波动性,有时会给机构或投资者带来巨大损失。考虑到股票市场的…...

实验三 JDBC数据库操作编程(设计性)
实验三 JDBC数据库操作编程(设计性) 实验目的 掌握JDBC的数据库编程方法。掌握采用JDBC完成数据库链接、增删改查,以及操作封装的综合应用。实验要求 本实验要求每个同学单独完成;调试程序要记录调试过程中出现的问题及解决办法…...
各种环境换源教程
目录 pip 换源相关命令永久换源1. 命令行换源2. 配置文件换源 临时换源使用官方源使用镜像源 报错参考 npm换源相关命令永久换源1. 命令行换源2. 配置文件换源 pip 换源 相关命令 更新 pip 本身 首先,为了确保你使用的是最新版本的 pip,可以通过以下命…...
Rust项目中的Labels
姊妹篇: Go项目中的Labels 按照issue数量从多到少排序: https://github.com/rust-lang/rust/labels?page2&sortcount-desc https://github.com/rust-lang/rust/labels/A-contributor-roadblock 第1页: 标签/中文说明数字T-compiler/编译器Relevant to the compiler tea…...

Jmeter的安装和使用
使用场景: 我们需要对某个接口进行压力测试,在多线程环境下,服务的抗压能力;还有就是关于分布式开发需要测试多线程环境下数据的唯一性。 解决方案: jmeter官网连接:Apache JMeter - Apache JMeter™ 下载安装包 配…...

初识Electron 进程通信
概述 Electron chromium nodejs native API,也就是将node环境和浏览器环境整合到了一起,这样就构成了桌面端(chromium负责渲染、node负责操作系统API等) 流程模型 预加载脚本:运行在浏览器环境下,但是…...
go语言中的通道(channel)详解
在 Go 语言中,通道(channel) 是一种用于在 goroutine(协程)之间传递数据的管道。通道具有类型安全性,即它只能传递一种指定类型的数据。通道是 Go 并发编程的重要特性,能够让多个 goroutine 之间…...
【JS】内置类型的相关问题
我是目录 引言内置类型undefined与nullnull和undefined的区别字符串转换为字符串数字0.1+0.2不等于0.3NaNBigInt大数相加问题原生函数(封箱与解封)判断类型的方法typeofinstanceofObject.prototype.toString.callconstructor类型转换toStringtoNumbertoBoolean显式强制类型转…...

Mac上无法访问usr/local的文件
sudo chmod 755 /usr/loca 最后用百度提供的方法解决了...
http 常见状态码
1xx 信息,表示临时响应并需要请求者继续执行操作 2xx 成功,操作被成功接收并处理 3xx 表示要完成请求,需要进一步操作。通常,这些状态码用来重定向 4xx 客户端错误,请求包含语法错误或无法完成请求 5xx 服务…...
代码训练营 day59|并查集
前言 这里记录一下陈菜菜的刷题记录,主要应对25秋招、春招 个人背景 211CS本CUHK计算机相关硕,一年车企软件开发经验 代码能力:有待提高 常用语言:C 系列文章目录 第59天 :第十一章:图论part05 文章目录…...

Node.js——fs模块-路径补充说明
1、相对路径: ./座右铭.txt 当前目录下的座右铭.txt座右铭.txt 等效于上面的写法../座右铭.txt 当前目录的上一级目录中的座右铭.txt 2、绝对路径 D:/Program File Windows系统下的绝对路径/usr/bin Linux系统…...
Python|GIF 解析与构建(5):手搓截屏和帧率控制
目录 Python|GIF 解析与构建(5):手搓截屏和帧率控制 一、引言 二、技术实现:手搓截屏模块 2.1 核心原理 2.2 代码解析:ScreenshotData类 2.2.1 截图函数:capture_screen 三、技术实现&…...
挑战杯推荐项目
“人工智能”创意赛 - 智能艺术创作助手:借助大模型技术,开发能根据用户输入的主题、风格等要求,生成绘画、音乐、文学作品等多种形式艺术创作灵感或初稿的应用,帮助艺术家和创意爱好者激发创意、提高创作效率。 - 个性化梦境…...

超短脉冲激光自聚焦效应
前言与目录 强激光引起自聚焦效应机理 超短脉冲激光在脆性材料内部加工时引起的自聚焦效应,这是一种非线性光学现象,主要涉及光学克尔效应和材料的非线性光学特性。 自聚焦效应可以产生局部的强光场,对材料产生非线性响应,可能…...
《Playwright:微软的自动化测试工具详解》
Playwright 简介:声明内容来自网络,将内容拼接整理出来的文档 Playwright 是微软开发的自动化测试工具,支持 Chrome、Firefox、Safari 等主流浏览器,提供多语言 API(Python、JavaScript、Java、.NET)。它的特点包括&a…...
【JavaSE】绘图与事件入门学习笔记
-Java绘图坐标体系 坐标体系-介绍 坐标原点位于左上角,以像素为单位。 在Java坐标系中,第一个是x坐标,表示当前位置为水平方向,距离坐标原点x个像素;第二个是y坐标,表示当前位置为垂直方向,距离坐标原点y个像素。 坐标体系-像素 …...

Java面试专项一-准备篇
一、企业简历筛选规则 一般企业的简历筛选流程:首先由HR先筛选一部分简历后,在将简历给到对应的项目负责人后再进行下一步的操作。 HR如何筛选简历 例如:Boss直聘(招聘方平台) 直接按照条件进行筛选 例如:…...
Linux C语言网络编程详细入门教程:如何一步步实现TCP服务端与客户端通信
文章目录 Linux C语言网络编程详细入门教程:如何一步步实现TCP服务端与客户端通信前言一、网络通信基础概念二、服务端与客户端的完整流程图解三、每一步的详细讲解和代码示例1. 创建Socket(服务端和客户端都要)2. 绑定本地地址和端口&#x…...
Go 语言并发编程基础:无缓冲与有缓冲通道
在上一章节中,我们了解了 Channel 的基本用法。本章将重点分析 Go 中通道的两种类型 —— 无缓冲通道与有缓冲通道,它们在并发编程中各具特点和应用场景。 一、通道的基本分类 类型定义形式特点无缓冲通道make(chan T)发送和接收都必须准备好࿰…...

基于PHP的连锁酒店管理系统
有需要请加文章底部Q哦 可远程调试 基于PHP的连锁酒店管理系统 一 介绍 连锁酒店管理系统基于原生PHP开发,数据库mysql,前端bootstrap。系统角色分为用户和管理员。 技术栈 phpmysqlbootstrapphpstudyvscode 二 功能 用户 1 注册/登录/注销 2 个人中…...

沙箱虚拟化技术虚拟机容器之间的关系详解
问题 沙箱、虚拟化、容器三者分开一一介绍的话我知道他们各自都是什么东西,但是如果把三者放在一起,它们之间到底什么关系?又有什么联系呢?我不是很明白!!! 就比如说: 沙箱&#…...