平面设计师推荐网站施工企业科技创新规划
web/
2025/10/3 21:20:47/
文章来源:
平面设计师推荐网站,施工企业科技创新规划,电脑网站打不开是什么原因造成的,阳江 网站建设一、HashMap是什么#xff0c;怎么用
1、HashMap是什么
HashMap 也是 Rust 标准库中提供的集合类型#xff0c;但是又与动态数组不同#xff0c;HashMap 中存储的是一一映射的 KV 键值对#xff0c;并提供了平均时间复杂度为 O(1) 的查询方法。
2、HashMap怎么用
…一、HashMap是什么怎么用
1、HashMap是什么
HashMap 也是 Rust 标准库中提供的集合类型但是又与动态数组不同HashMap 中存储的是一一映射的 KV 键值对并提供了平均时间复杂度为 O(1) 的查询方法。
2、HashMap怎么用
1创建哈希表
使用new 方法创建
use std::collections::HashMap;//注意要导入包// 创建一个HashMap用于存储宝石种类和对应的数量
let mut my_gems HashMap::new();// 将宝石类型和对应的数量写入表中
my_gems.insert(红宝石, 1);
my_gems.insert(蓝宝石, 2);
my_gems.insert(河边捡的误以为是宝石的破石头, 18);使用collection创建
fn main() {use std::collections::HashMap;let teams_list vec![(中国队.to_string(), 100),(美国队.to_string(), 10),(日本队.to_string(), 50),];let teams_map: HashMap_,_ teams_list.into_iter().collect();println!({:?},teams_map)
}元组数据直接创建
use std::{collections::HashMap};
fn main() {let teams [(Chinese Team, 100),(American Team, 10),(France Team, 50),];let mut teams_map1 HashMap::new();for team in teams {teams_map1.insert(team.0, team.1);}let teams_map2 HashMap::from(teams);assert_eq!(teams_map1, teams_map2);println!(Success!)
}2哈希表的元素所有权转移
即放入元素到哈希表中也会发生所有权转移
fn main() {use std::collections::HashMap;let name String::from(Sunface);let age 18;let mut handsome_boys HashMap::new();handsome_boys.insert(name, age);println!(因为过于无耻{}已经被从帅气男孩名单中除名, name);println!(还有他的真实年龄远远不止{}岁, age);
}3 获取哈希表中的元素
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: Optioni32 scores.get(team_name);get 方法返回一个 Optioni32 类型当查询不到时会返回一个 None查询到时返回 Some(i32)i32是对 HashMap 中值的借用如果不使用借用可能会发生所有权的转移
4遍历哈希表中的元素
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);
}5哈希表插入新值
fn main() {use std::collections::HashMap;let mut scores HashMap::new();scores.insert(Blue, 10);
}6没有则插入
fn main() {use std::collections::HashMap;let mut scores HashMap::new();scores.insert(Blue, 10);// 查询Yellow对应的值若不存在则插入新值let v scores.entry(Yellow).or_insert(5);assert_eq!(*v, 5); // 不存在插入5
}7已有则更新
fn main() {use std::collections::HashMap;let mut scores HashMap::new();scores.insert(Blue, 10);// 覆盖已有的值let old scores.insert(Blue, 20);//覆盖assert_eq!(old, Some(10));}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/86421.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!