diff options
author | Orangerot <purple@orangerot.dev> | 2024-06-27 11:30:16 +0200 |
---|---|---|
committer | Orangerot <purple@orangerot.dev> | 2024-06-27 11:30:16 +0200 |
commit | 4b0a6a01b051a4ebfbc17661d14cb23fe4f275fb (patch) | |
tree | 0072cca328fe5adb2ed61004010228ff85e2164d /design-hashmap |
Diffstat (limited to 'design-hashmap')
-rw-r--r-- | design-hashmap/Cargo.toml | 8 | ||||
-rw-r--r-- | design-hashmap/src/main.rs | 43 |
2 files changed, 51 insertions, 0 deletions
diff --git a/design-hashmap/Cargo.toml b/design-hashmap/Cargo.toml new file mode 100644 index 0000000..5f27b3e --- /dev/null +++ b/design-hashmap/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "design-hashmap" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/design-hashmap/src/main.rs b/design-hashmap/src/main.rs new file mode 100644 index 0000000..f35bd69 --- /dev/null +++ b/design-hashmap/src/main.rs @@ -0,0 +1,43 @@ +fn main() { + println!("Hello, world!"); + let mut a = MyHashMap::new(); + a.put(1,1); + a.put(2,2); + a.get(1); + a.get(3); + a.put(2,1); + a.get(2); + a.remove(2); + a.get(2); +} + +struct MyHashMap { + map: Vec<(i32,i32)> +} + +impl MyHashMap { + + fn new() -> Self { + MyHashMap { + map: Vec::new() + } + } + + fn put(&mut self, key: i32, value: i32) { + match self.map.iter_mut().find(|x| x.0 == key) { + Some(e) => e.1 = value, + None => self.map.push((key, value)) + }; + } + + fn get(&self, key: i32) -> i32 { + self.map.iter().find(|&x| x.0 == key).map(|x| x.1).unwrap_or(-1) + } + + fn remove(&mut self, key: i32) { + if let Some(e) = self.map.iter().position(|x| x.0 == key) { + self.map.swap_remove(e); + } + } +} + |