Rus入门到放弃——HashMap和BTreeMap
生活随笔
收集整理的這篇文章主要介紹了
Rus入门到放弃——HashMap和BTreeMap
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
概述
1.HashMap和BTreeMap都是通過鍵值對來存儲數據,一個Key對應一個Value,同構。
2.HashMap和BTreeMap是通過鍵值(任何類型)來查找數據,而不是通過索引,鍵值是唯一的存在。
3.HashMap的key是可哈希,BTreeMap的key 可排序,HashMap無序,BTreeMap有序。
4.HashMap和BTreeMap的數據存儲在堆內存中。
示例
聲明
//聲明與賦值let mut hash_map = HashMap::new();//let mut hash:HashMap<String,u32> = HashMap::new();hash_map.insert(String::from("Red"), 10);hash_map.insert(String::from("Blue"), 225);collect方法合成
let teams = vec![String::from("R"),String::from("G"),String::from("B"),String::from("A")];let intial = vec![20,100,255,127];//合成一個hashmaplet map:HashMap<_,_> = teams.iter().zip(intial.iter()).collect();訪問
//訪問let color = String::from("B");let value = map.get(&color);match value {Some(s) => println!("{}",s),None => println!("Not value"),};遍歷
//遍歷for (k,v) in &map{println!("{} - {} ", k,v);}更新HashMap中的數據, 替換現有的值, 保留再有的值,忽略新的值,合并現有的值和新的值。
//更新hash_map.insert(String::from("Red"), 222);println!("{:?}",hash_map);//判斷是否存在再插入,存在則不插入hash_map.entry(String::from("Red")).or_insert(50);hash_map.entry(String::from("Yellow")).or_insert(100);println!("{:?}",hash_map);let text = "hello world woderful world";let mut map = HashMap::new();for word in text.split_whitespace(){let count = map.entry(word).or_insert(0);*count += 1;}println!("{:#?}",map);總結
以上是生活随笔為你收集整理的Rus入门到放弃——HashMap和BTreeMap的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 智能老旧模糊照片修复——C++实现GFP
- 下一篇: 基于Yolov5的烟火检测——模型训练与