C++库之哈希表

C++标准库中有哈希表,直接调用即可,包括哦unordered_map和unordered_set,使用之前需要引用头文件

#include <unordered_map>
#include <unordered_set>

分别介绍一下unordered_map和unordered_set内置的函数

一.unordered_map

    unordered_map<int, int> hashmap;
    hashmap[1]=19;
    hashmap.insert({1,3});
    hashmap[1]++;
    hashmap.insert({2,10});
    cout << hashmap[1] << endl;
    cout << hashmap[3] << endl;
    cout << hashmap.count(1) << endl;

结果

20
0
1

二.unordered_set

.insert(X):插入元素。
.erase():删除元素。
.count():记录元素个数,实际上hashset只对元素记录一遍,有的话是1,没有为0,重复插入无效
.find(X); 查找元素,有的话返回指向该元素的迭代器,没有的话返回尾后迭代器
.clear():清除所有元素
.size() :返回哈希大小

2.1 测试代码

    unordered_set<int> hashset;
    hashset.insert(1);
    hashset.insert(2);
    cout << *hashset.find(2)<< endl;
    cout << hashset.count(2) << endl;
    hashset.insert(2);
    cout << hashset.count(2) << endl;
    hashset.erase(2);
    cout << hashset.count(2) << endl;
    hashset.insert(2);
    auto it = hashset.find(2);
    cout << *it << endl;
    auto it2 = hashset.find(3);
    if (it2 == hashset.end())
        cout << "没有元素3" << endl;
    hashset.clear();
    auto it3 = hashset.find(1);
    if (it3 == hashset.end())
        cout << "元素清空,没有元素1" << endl;
    cout << "现在hashset尺寸为" << hashset.size() << endl;

2.2 输出结果

2
1
1
0
2
没有元素3
元素清空,没有元素1
现在hashset尺寸为0

  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值