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

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 组件&#xff0c;依赖 tooltip 组件&#xff1b;当 tooltip 的 trigger 的值不是 hover 时&#xff0c;会触发 close 事件&#xff1b;下拉框的 click 事件&#xff0c;触发了 tooltip 组件的 close 事件 总结一下&am…...

SQLI LABS | Less-37 POST-Bypass mysql_real_escape_string

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

数字后端零基础入门系列 | Innovus零基础LAB学习Day9

Module 16 Wire Editing 这个章节的学习目标是学习如何在innovus中手工画线&#xff0c;切断一根线&#xff0c;换孔&#xff0c;更改一条net shape的layer和width等等。这个技能是每个数字IC后端工程师必须具备的。因为项目后期都需要这些技能来修复DRC和做一些手工custom走线…...

深度学习:GLUE(General Language Understanding Evaluation)详解

GLUE&#xff08;General Language Understanding Evaluation&#xff09;详解 GLUE&#xff08;General Language Understanding Evaluation&#xff09;是一个用于评估和比较自然语言理解&#xff08;NLU&#xff09;系统的综合基准测试。它包括了一系列的任务&#xff0c;旨…...

基于Multisim直流稳压电源电路±9V、±5V(含仿真和报告)

【全套资料.zip】直流稳压电源电路9V、5VMultisim仿真设计数字电子技术 文章目录 功能一、Multisim仿真源文件二、原理文档报告资料下载【Multisim仿真报告讲解视频.zip】 功能 一般直流稳压电源都使用220伏市电作为电源&#xff0c;经过变压、整流、滤波后给稳压电路进行稳压…...

Vue Cli的配置中configureWebpack和chainWebpack的主要作用及区别是什么?

直接区别&#xff1a; configureWebpack项直接覆盖同名配置&#xff1b;chainWebpack项直接修改默认配置。 configureWebpack配置&#xff1a; // 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 &#xff0c;ubuntu22.04,aarch64 ,cpu rk3588s targetubuntu22.04target-archaarch64target-cpurk3588s 安装 qemu-user-static 进入 …...

Python注意力机制Attention下CNN-LSTM-ARIMA混合模型预测中国银行股票价格|附数据代码...

全文链接&#xff1a;https://tecdat.cn/?p38195 股票市场在经济发展中占据重要地位。由于股票的高回报特性&#xff0c;股票市场吸引了越来越多机构和投资者的关注。然而&#xff0c;由于股票市场的复杂波动性&#xff0c;有时会给机构或投资者带来巨大损失。考虑到股票市场的…...

实验三 JDBC数据库操作编程(设计性)

实验三 JDBC数据库操作编程&#xff08;设计性&#xff09; 实验目的 掌握JDBC的数据库编程方法。掌握采用JDBC完成数据库链接、增删改查&#xff0c;以及操作封装的综合应用。实验要求 本实验要求每个同学单独完成&#xff1b;调试程序要记录调试过程中出现的问题及解决办法…...

各种环境换源教程

目录 pip 换源相关命令永久换源1. 命令行换源2. 配置文件换源 临时换源使用官方源使用镜像源 报错参考 npm换源相关命令永久换源1. 命令行换源2. 配置文件换源 pip 换源 相关命令 更新 pip 本身 首先&#xff0c;为了确保你使用的是最新版本的 pip&#xff0c;可以通过以下命…...

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的安装和使用

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

初识Electron 进程通信

概述 Electron chromium nodejs native API&#xff0c;也就是将node环境和浏览器环境整合到了一起&#xff0c;这样就构成了桌面端&#xff08;chromium负责渲染、node负责操作系统API等&#xff09; 流程模型 预加载脚本&#xff1a;运行在浏览器环境下&#xff0c;但是…...

go语言中的通道(channel)详解

在 Go 语言中&#xff0c;通道&#xff08;channel&#xff09; 是一种用于在 goroutine&#xff08;协程&#xff09;之间传递数据的管道。通道具有类型安全性&#xff0c;即它只能传递一种指定类型的数据。通道是 Go 并发编程的重要特性&#xff0c;能够让多个 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 信息&#xff0c;表示临时响应并需要请求者继续执行操作 2xx 成功&#xff0c;操作被成功接收并处理 3xx 表示要完成请求&#xff0c;需要进一步操作。通常&#xff0c;这些状态码用来重定向 4xx 客户端错误&#xff0c;请求包含语法错误或无法完成请求 5xx 服务…...

代码训练营 day59|并查集

前言 这里记录一下陈菜菜的刷题记录&#xff0c;主要应对25秋招、春招 个人背景 211CS本CUHK计算机相关硕&#xff0c;一年车企软件开发经验 代码能力&#xff1a;有待提高 常用语言&#xff1a;C 系列文章目录 第59天 &#xff1a;第十一章&#xff1a;图论part05 文章目录…...

Node.js——fs模块-路径补充说明

1、相对路径&#xff1a; ./座右铭.txt 当前目录下的座右铭.txt座右铭.txt 等效于上面的写法../座右铭.txt 当前目录的上一级目录中的座右铭.txt 2、绝对路径 D&#xff1a;/Program File Windows系统下的绝对路径/usr/bin Linux系统…...

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…...

Qt/C++开发监控GB28181系统/取流协议/同时支持udp/tcp被动/tcp主动

一、前言说明 在2011版本的gb28181协议中&#xff0c;拉取视频流只要求udp方式&#xff0c;从2016开始要求新增支持tcp被动和tcp主动两种方式&#xff0c;udp理论上会丢包的&#xff0c;所以实际使用过程可能会出现画面花屏的情况&#xff0c;而tcp肯定不丢包&#xff0c;起码…...

k8s从入门到放弃之Ingress七层负载

k8s从入门到放弃之Ingress七层负载 在Kubernetes&#xff08;简称K8s&#xff09;中&#xff0c;Ingress是一个API对象&#xff0c;它允许你定义如何从集群外部访问集群内部的服务。Ingress可以提供负载均衡、SSL终结和基于名称的虚拟主机等功能。通过Ingress&#xff0c;你可…...

Java多线程实现之Thread类深度解析

Java多线程实现之Thread类深度解析 一、多线程基础概念1.1 什么是线程1.2 多线程的优势1.3 Java多线程模型 二、Thread类的基本结构与构造函数2.1 Thread类的继承关系2.2 构造函数 三、创建和启动线程3.1 继承Thread类创建线程3.2 实现Runnable接口创建线程 四、Thread类的核心…...

【Redis】笔记|第8节|大厂高并发缓存架构实战与优化

缓存架构 代码结构 代码详情 功能点&#xff1a; 多级缓存&#xff0c;先查本地缓存&#xff0c;再查Redis&#xff0c;最后才查数据库热点数据重建逻辑使用分布式锁&#xff0c;二次查询更新缓存采用读写锁提升性能采用Redis的发布订阅机制通知所有实例更新本地缓存适用读多…...

MySQL JOIN 表过多的优化思路

当 MySQL 查询涉及大量表 JOIN 时&#xff0c;性能会显著下降。以下是优化思路和简易实现方法&#xff1a; 一、核心优化思路 减少 JOIN 数量 数据冗余&#xff1a;添加必要的冗余字段&#xff08;如订单表直接存储用户名&#xff09;合并表&#xff1a;将频繁关联的小表合并成…...

CRMEB 中 PHP 短信扩展开发:涵盖一号通、阿里云、腾讯云、创蓝

目前已有一号通短信、阿里云短信、腾讯云短信扩展 扩展入口文件 文件目录 crmeb\services\sms\Sms.php 默认驱动类型为&#xff1a;一号通 namespace crmeb\services\sms;use crmeb\basic\BaseManager; use crmeb\services\AccessTokenServeService; use crmeb\services\sms\…...

接口自动化测试:HttpRunner基础

相关文档 HttpRunner V3.x中文文档 HttpRunner 用户指南 使用HttpRunner 3.x实现接口自动化测试 HttpRunner介绍 HttpRunner 是一个开源的 API 测试工具&#xff0c;支持 HTTP(S)/HTTP2/WebSocket/RPC 等网络协议&#xff0c;涵盖接口测试、性能测试、数字体验监测等测试类型…...

Git 3天2K星标:Datawhale 的 Happy-LLM 项目介绍(附教程)

引言 在人工智能飞速发展的今天&#xff0c;大语言模型&#xff08;Large Language Models, LLMs&#xff09;已成为技术领域的焦点。从智能写作到代码生成&#xff0c;LLM 的应用场景不断扩展&#xff0c;深刻改变了我们的工作和生活方式。然而&#xff0c;理解这些模型的内部…...

OD 算法题 B卷【正整数到Excel编号之间的转换】

文章目录 正整数到Excel编号之间的转换 正整数到Excel编号之间的转换 excel的列编号是这样的&#xff1a;a b c … z aa ab ac… az ba bb bc…yz za zb zc …zz aaa aab aac…; 分别代表以下的编号1 2 3 … 26 27 28 29… 52 53 54 55… 676 677 678 679 … 702 703 704 705;…...