Skip to content

Commit 0a3d394

Browse files
authored
Merge pull request #1681 from rongyi/main
tiny fix, more readable rust
2 parents 7e904c8 + bd03b8c commit 0a3d394

File tree

1 file changed

+10
-14
lines changed

1 file changed

+10
-14
lines changed

codes/rust/chapter_hashing/hash_map_chaining.rs

+10-14
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,10 @@ struct Pair {
1313

1414
/* 链式地址哈希表 */
1515
struct HashMapChaining {
16-
size: i32,
17-
capacity: i32,
16+
size: usize,
17+
capacity: usize,
1818
load_thres: f32,
19-
extend_ratio: i32,
19+
extend_ratio: usize,
2020
buckets: Vec<Vec<Pair>>,
2121
}
2222

@@ -34,7 +34,7 @@ impl HashMapChaining {
3434

3535
/* 哈希函数 */
3636
fn hash_func(&self, key: i32) -> usize {
37-
key as usize % self.capacity as usize
37+
key as usize % self.capacity
3838
}
3939

4040
/* 负载因子 */
@@ -45,12 +45,11 @@ impl HashMapChaining {
4545
/* 删除操作 */
4646
fn remove(&mut self, key: i32) -> Option<String> {
4747
let index = self.hash_func(key);
48-
let bucket = &mut self.buckets[index];
4948

5049
// 遍历桶,从中删除键值对
51-
for i in 0..bucket.len() {
52-
if bucket[i].key == key {
53-
let pair = bucket.remove(i);
50+
for (i, p) in self.buckets[index].iter_mut().enumerate() {
51+
if p.key == key {
52+
let pair = self.buckets[index].remove(i);
5453
self.size -= 1;
5554
return Some(pair.val);
5655
}
@@ -97,30 +96,27 @@ impl HashMapChaining {
9796
}
9897

9998
let index = self.hash_func(key);
100-
let bucket = &mut self.buckets[index];
10199

102100
// 遍历桶,若遇到指定 key ,则更新对应 val 并返回
103-
for pair in bucket {
101+
for pair in self.buckets[index].iter_mut() {
104102
if pair.key == key {
105103
pair.val = val;
106104
return;
107105
}
108106
}
109-
let bucket = &mut self.buckets[index];
110107

111108
// 若无该 key ,则将键值对添加至尾部
112109
let pair = Pair { key, val };
113-
bucket.push(pair);
110+
self.buckets[index].push(pair);
114111
self.size += 1;
115112
}
116113

117114
/* 查询操作 */
118115
fn get(&self, key: i32) -> Option<&str> {
119116
let index = self.hash_func(key);
120-
let bucket = &self.buckets[index];
121117

122118
// 遍历桶,若找到 key ,则返回对应 val
123-
for pair in bucket {
119+
for pair in self.buckets[index].iter() {
124120
if pair.key == key {
125121
return Some(&pair.val);
126122
}

0 commit comments

Comments
 (0)