"首次提交"
This commit is contained in:
1
hash_map/.gitignore
vendored
Executable file
1
hash_map/.gitignore
vendored
Executable file
@ -0,0 +1 @@
|
||||
/target
|
8
hash_map/Cargo.toml
Executable file
8
hash_map/Cargo.toml
Executable file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "hash_map"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
46
hash_map/src/main.rs
Executable file
46
hash_map/src/main.rs
Executable file
@ -0,0 +1,46 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn main() {
|
||||
println!("Hello, world!");
|
||||
hash_map_learn();
|
||||
}
|
||||
|
||||
|
||||
fn hash_map_learn() {
|
||||
|
||||
/* 创建一个hashmap,使用显式指定key和value的类型的方式
|
||||
创建时也可以不指定类型,使用insert方法进行元素的插入时即可自动推导出类型
|
||||
不过一旦类型确定所有key的类型必须一致。所有value的类型也必须一致。
|
||||
*/
|
||||
let mut map1:HashMap<String, i32> = HashMap::new();
|
||||
|
||||
//插入一个元素
|
||||
map1.insert(String::from("aa"), 1);
|
||||
//插入同名元素,会覆盖原有的元素
|
||||
map1.insert(String::from("aa"), 2);
|
||||
println!("{:?}", map1);
|
||||
//尝试访问并在没有对应数据的情况下插入新的值,这样可以做到不覆盖已有元素
|
||||
map1.entry(String::from("aa")).or_insert(3);// 如果元素aa不存在则插入aa:3
|
||||
map1.entry(String::from("bb")).or_insert(4);// 如果元素aa不存在则插入bb:4
|
||||
println!("{:?}", map1);
|
||||
|
||||
let e = map1.entry(String::from("cc"));
|
||||
println!("{:?}", e);
|
||||
let e = map1.entry(String::from("aa"));
|
||||
println!("{:?}", e);
|
||||
|
||||
//利用hashmap统计单词的个数。
|
||||
let str1 = String::from("hello world wonderful world 你好 世界 美丽 世界");
|
||||
let mut map1 = HashMap::new();
|
||||
//将单词使用空格切割开 并遍历
|
||||
for word in str1.split_whitespace() {
|
||||
//这里or_insert的返回值是hashmap对应word的键值对的值的可变引用,
|
||||
//这里就是如果没找到word那么就插入一个word和cnt的键值对。值就是0。并将值的可变引用返回
|
||||
//这里如果找到对应的word那么就不会覆盖原来的值,仅仅是将值的可变引用返回
|
||||
//所以无论如何我们都能获得一个该word对应出现次数的可变引用
|
||||
let count = map1.entry(word).or_insert(0);
|
||||
//将值所对应的可变引用进行+1,表示数字个数多了一个
|
||||
*count = *count + 1;
|
||||
}
|
||||
println!("{:?}", map1);
|
||||
}
|
Reference in New Issue
Block a user