[哈希表] lg-P5266 【深基17.例6】学籍管理(哈希表+unordered_map()坑点+模板题)

1. 题目来源

链接:P5266 【深基17.例6】学籍管理

2. 题目解析

水题,unordered_map<> 基本使用。

坑点:

  • unordered_map 即哈希表,不论对其赋值与否都会在哈希表中插入这个值,即 res += hash[t],若 t 查找不到则 res += 0 也不影响正确结果,但是这个无用的 t 会被插入到哈希表中。

代码:

// https://www.luogu.com.cn/problem/P5266

#include <iostream>
#include <cstdio>
#include <string>
#include <unordered_map>

using namespace std;

int n;
unordered_map<string, int> h;

int main() {
    scanf("%d", &n);
    for (int i = 0; i < n; i ++ ) {
        int op;
        string s;
        int sum;
        scanf("%d", &op);
        if (op == 1) {
            cin >> s >> sum;
            h[s] = sum, printf("OK\n");
        }
        else if (op == 2) {
            cin >> s;
            if (h.count(s)) printf("%d\n", h[s]);
            else printf("Not found\n");
        }
        else if (op == 3) {
            cin >> s;
            if (h.count(s)) h.erase(s), printf("Deleted successfully\n");
            else printf("Not found\n");
        }
        else printf("%d\n", h.size());
    }
}

测试代码:

#include <iostream>
#include <unordered_map>

using namespace std;

int main() {
    unordered_map<int, int> h;
    h[1] = 1;
    h[2] = 2;
    cout << h.size() << endl;
    if (h.find(3) != h.end()) cout << 1 << endl;
    int res = 0;
    res += h[3];
    if (h.count(3)) cout << 2 << endl;
    cout << h.size() << ' ' << res << endl;
    return 0;
}

/*
2
2
3 0
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Ypuyu

如果帮助到你,可以请作者喝水~

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

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

打赏作者

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

抵扣说明:

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

余额充值