【C++】二维数组、指针数组 new 及 delete 用法,hash_map demo 实现


一、前言

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
------

三、小结

对文章内容有不解,请随时留言。


  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

idiot5liev

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值