mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-06 14:27:26 +08:00
Fixed some problems, indentation and Pointer
This commit is contained in:
@ -15,17 +15,16 @@ public:
|
||||
this->key = key;
|
||||
this->val = val;
|
||||
}
|
||||
Entry()=default;
|
||||
};
|
||||
|
||||
/* 基于数组简易实现的哈希表 */
|
||||
class ArrayHashMap {
|
||||
private:
|
||||
vector<Entry> bucket;
|
||||
vector<Entry*> bucket;
|
||||
public:
|
||||
ArrayHashMap() {
|
||||
// 初始化一个长度为 100 的桶(数组)
|
||||
bucket= vector<Entry>(100);
|
||||
bucket= vector<Entry*>(100);
|
||||
}
|
||||
|
||||
/* 哈希函数 */
|
||||
@ -37,13 +36,16 @@ public:
|
||||
/* 查询操作 */
|
||||
string get(int key) {
|
||||
int index = hashFunc(key);
|
||||
Entry pair = bucket[index];
|
||||
return pair.val;
|
||||
Entry* pair = bucket[index];
|
||||
if (pair == nullptr) {
|
||||
return "Not Found";
|
||||
}
|
||||
return pair->val;
|
||||
}
|
||||
|
||||
/* 添加操作 */
|
||||
void put(int key, string val) {
|
||||
Entry pair = Entry(key, val);
|
||||
Entry* pair = new Entry(key, val);
|
||||
int index = hashFunc(key);
|
||||
bucket[index] = pair;
|
||||
}
|
||||
@ -52,14 +54,14 @@ public:
|
||||
void remove(int key) {
|
||||
int index = hashFunc(key);
|
||||
// 置为空字符,代表删除
|
||||
bucket[index] = *new Entry();
|
||||
bucket[index] = nullptr;
|
||||
}
|
||||
|
||||
/* 获取所有键值对 */
|
||||
vector<Entry> entrySet() {
|
||||
vector<Entry> entrySet;
|
||||
for (Entry pair: bucket) {
|
||||
if (pair.key != 0) {
|
||||
vector<Entry*> entrySet() {
|
||||
vector<Entry*> entrySet;
|
||||
for (Entry* pair: bucket) {
|
||||
if (pair != nullptr) {
|
||||
entrySet.push_back(pair);
|
||||
}
|
||||
}
|
||||
@ -69,9 +71,9 @@ public:
|
||||
/* 获取所有键 */
|
||||
vector<int> keySet() {
|
||||
vector<int> keySet;
|
||||
for (Entry pair: bucket) {
|
||||
if (pair.key != 0) {
|
||||
keySet.push_back(pair.key);
|
||||
for (Entry* pair: bucket) {
|
||||
if (pair != nullptr) {
|
||||
keySet.push_back(pair->key);
|
||||
}
|
||||
}
|
||||
return keySet;
|
||||
@ -80,17 +82,18 @@ public:
|
||||
/* 获取所有值 */
|
||||
vector<string> valueSet() {
|
||||
vector<string> valueSet;
|
||||
for (Entry pair: bucket) {
|
||||
if (pair.key != 0)
|
||||
valueSet.push_back(pair.val);
|
||||
for (Entry* pair: bucket) {
|
||||
if (pair != nullptr){
|
||||
valueSet.push_back(pair->val);
|
||||
}
|
||||
}
|
||||
return valueSet;
|
||||
}
|
||||
|
||||
/* 打印哈希表 */
|
||||
void print() {
|
||||
for (Entry kv: entrySet()) {
|
||||
cout << kv.key << " -> " << kv.val << endl;
|
||||
for (Entry* kv: entrySet()) {
|
||||
cout << kv->key << " -> " << kv->val << endl;
|
||||
}
|
||||
}
|
||||
};
|
||||
@ -122,7 +125,7 @@ int main() {
|
||||
/* 遍历哈希表 */
|
||||
cout << "\n遍历键值对 Key->Value" << endl;
|
||||
for (auto kv: map.entrySet()) {
|
||||
cout << kv.key << " -> " << kv.val << endl;
|
||||
cout << kv->key << " -> " << kv->val << endl;
|
||||
}
|
||||
|
||||
cout << "\n单独遍历键 Key" << endl;
|
||||
|
Reference in New Issue
Block a user