一、前言
C++ 堆空间变量,包括平时写算法题,通常 new 单一变量,偶然发现自己并没有真正掌握 new 二维数组即 new 指针数组,故写下此文,并附上 hash_map demo 实现。
// 二维数组、指针数组 new 及 delete 用法
#include <iostream>
using namespace std;
int main() {
// new, 方法 a
// int (*p)[10] = new int[5][10];
// delete, 方法 a
// delete []p;
// new, 方法 b
int **p = new int*[5];
for (int i = 0; i < 5; ++i) {
p[i] = new int[10];
}
// delete, 方法 b
for (int i = 0; i < 5; ++i) {
delete []p[i];
}
delete []p;
return 0;
}
二、new 指针数组 hash_map demo 实现
代码验证:
// 简易 hash_map 原理及实现, 解决冲突拉链法
#include <iostream>
using namespace std;
struct Node {
int key;
string val;
Node *next;
Node(): key(0), val(""), next(nullptr) {}
Node(int key, string val): key(key), val(val), next(nullptr) {}
};
Node **hash_map = new Node*[16]; // 第一次 new 二维指针
void init() {
for (int i = 0; i < 16; ++i) {
hash_map[i] = new Node(); // 默认构造初始化指针数组成员
}
return ;
}
void set(int key, string val) {
int ind = key % 16;
Node *cur = hash_map[ind];
while (cur->next) {
if (cur->next->key == key) {
cur->next->val = val;
return ;
}
cur = cur->next;
}
Node *node = new Node(key, val);
cur->next = node;
return ;
}
string get(int key) {
int ind = key % 16;
Node *cur = hash_map[ind];
while (cur->next) {
if (cur->next->key == key) {
return cur->next->val;
}
cur = cur->next;
}
return "-1";
}
int main() {
init();
cout << get(1) << endl;
set(1, "tiger");
cout << get(1) << endl;
set(2, "rabbit");
cout << get(2) << endl;
set(1, "hi");
cout << get(1) << endl;
cout << "------" << endl;
// TODO
return 0;
}
输出:
-1
tiger
rabbit
hi
------
三、小结
对文章内容有不解,请随时留言。