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系统…...
解锁数据库简洁之道:FastAPI与SQLModel实战指南
在构建现代Web应用程序时,与数据库的交互无疑是核心环节。虽然传统的数据库操作方式(如直接编写SQL语句与psycopg2交互)赋予了我们精细的控制权,但在面对日益复杂的业务逻辑和快速迭代的需求时,这种方式的开发效率和可…...
Qt Http Server模块功能及架构
Qt Http Server 是 Qt 6.0 中引入的一个新模块,它提供了一个轻量级的 HTTP 服务器实现,主要用于构建基于 HTTP 的应用程序和服务。 功能介绍: 主要功能 HTTP服务器功能: 支持 HTTP/1.1 协议 简单的请求/响应处理模型 支持 GET…...

ETLCloud可能遇到的问题有哪些?常见坑位解析
数据集成平台ETLCloud,主要用于支持数据的抽取(Extract)、转换(Transform)和加载(Load)过程。提供了一个简洁直观的界面,以便用户可以在不同的数据源之间轻松地进行数据迁移和转换。…...

OPENCV形态学基础之二腐蚀
一.腐蚀的原理 (图1) 数学表达式:dst(x,y) erode(src(x,y)) min(x,y)src(xx,yy) 腐蚀也是图像形态学的基本功能之一,腐蚀跟膨胀属于反向操作,膨胀是把图像图像变大,而腐蚀就是把图像变小。腐蚀后的图像变小变暗淡。 腐蚀…...
scikit-learn机器学习
# 同时添加如下代码, 这样每次环境(kernel)启动的时候只要运行下方代码即可: # Also add the following code, # so that every time the environment (kernel) starts, # just run the following code: import sys sys.path.append(/home/aistudio/external-libraries)机…...
学习一下用鸿蒙DevEco Studio HarmonyOS5实现百度地图
在鸿蒙(HarmonyOS5)中集成百度地图,可以通过以下步骤和技术方案实现。结合鸿蒙的分布式能力和百度地图的API,可以构建跨设备的定位、导航和地图展示功能。 1. 鸿蒙环境准备 开发工具:下载安装 De…...

保姆级【快数学会Android端“动画“】+ 实现补间动画和逐帧动画!!!
目录 补间动画 1.创建资源文件夹 2.设置文件夹类型 3.创建.xml文件 4.样式设计 5.动画设置 6.动画的实现 内容拓展 7.在原基础上继续添加.xml文件 8.xml代码编写 (1)rotate_anim (2)scale_anim (3)translate_anim 9.MainActivity.java代码汇总 10.效果展示 逐帧…...

对象回调初步研究
_OBJECT_TYPE结构分析 在介绍什么是对象回调前,首先要熟悉下结构 以我们上篇线程回调介绍过的导出的PsProcessType 结构为例,用_OBJECT_TYPE这个结构来解析它,0x80处就是今天要介绍的回调链表,但是先不着急,先把目光…...

麒麟系统使用-进行.NET开发
文章目录 前言一、搭建dotnet环境1.获取相关资源2.配置dotnet 二、使用dotnet三、其他说明总结 前言 麒麟系统的内核是基于linux的,如果需要进行.NET开发,则需要安装特定的应用。由于NET Framework 是仅适用于 Windows 版本的 .NET,所以要进…...

路由基础-路由表
本篇将会向读者介绍路由的基本概念。 前言 在一个典型的数据通信网络中,往往存在多个不同的IP网段,数据在不同的IP网段之间交互是需要借助三层设备的,这些设备具备路由能力,能够实现数据的跨网段转发。 路由是数据通信网络中最基…...