cpp-algo-cases/chapter_hashing/array_hash_map.cpp

111 lines
2.2 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: array_hash_map.cpp
* Created Time: 2022-12-14
* Author: msk397 (machangxinq@gmail.com)
*/
#include "../utils/common.hpp"
/* <20><>ֵ<EFBFBD><D6B5> */
struct Pair {
public:
int key;
string val;
Pair(int key, string val) {
this->key = key;
this->val = val;
}
};
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʵ<EFBFBD>ֵĹ<D6B5>ϣ<EFBFBD><CFA3> */
class ArrayHashMap {
private:
vector<Pair *> buckets;
public:
ArrayHashMap() {
// <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E9A3AC><EFBFBD><EFBFBD> 100 <20><>Ͱ
buckets = vector<Pair *>(100);
}
~ArrayHashMap() {
// <20>ͷ<EFBFBD><CDB7>ڴ<EFBFBD>
for (const auto &bucket : buckets) {
delete bucket;
}
buckets.clear();
}
/* <20><>ϣ<EFBFBD><CFA3><EFBFBD><EFBFBD> */
int hashFunc(int key) {
int index = key % 100;
return index;
}
/* <20><>ѯ<EFBFBD><D1AF><EFBFBD><EFBFBD> */
string get(int key) {
int index = hashFunc(key);
Pair *pair = buckets[index];
if (pair == nullptr)
return "";
return pair->val;
}
/* <20><><EFBFBD>Ӳ<EFBFBD><D3B2><EFBFBD> */
void put(int key, string val) {
Pair *pair = new Pair(key, val);
int index = hashFunc(key);
buckets[index] = pair;
}
/* ɾ<><C9BE><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
void remove(int key) {
int index = hashFunc(key);
// <20>ͷ<EFBFBD><CDB7>ڴ沢<DAB4><E6B2A2>Ϊ nullptr
delete buckets[index];
buckets[index] = nullptr;
}
/* <20><>ȡ<EFBFBD><C8A1><EFBFBD>м<EFBFBD>ֵ<EFBFBD><D6B5> */
vector<Pair *> pairSet() {
vector<Pair *> pairSet;
for (Pair *pair : buckets) {
if (pair != nullptr) {
pairSet.push_back(pair);
}
}
return pairSet;
}
/* <20><>ȡ<EFBFBD><C8A1><EFBFBD>м<EFBFBD> */
vector<int> keySet() {
vector<int> keySet;
for (Pair *pair : buckets) {
if (pair != nullptr) {
keySet.push_back(pair->key);
}
}
return keySet;
}
/* <20><>ȡ<EFBFBD><C8A1><EFBFBD><EFBFBD>ֵ */
vector<string> valueSet() {
vector<string> valueSet;
for (Pair *pair : buckets) {
if (pair != nullptr) {
valueSet.push_back(pair->val);
}
}
return valueSet;
}
/* <20><>ӡ<EFBFBD><D3A1>ϣ<EFBFBD><CFA3> */
void print() {
for (Pair *kv : pairSet()) {
cout << kv->key << " -> " << kv->val << endl;
}
}
};
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> array_hash_map_test.cpp