当前位置:   article > 正文

C++库之哈希表_c++哈希表删除元素

c++哈希表删除元素

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

#include <unordered_map>
#include <unordered_set>
  • 1
  • 2

分别介绍一下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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

结果

20
0
1
  • 1
  • 2
  • 3

二.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;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

2.2 输出结果

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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/808371?site
推荐阅读
相关标签
  

闽ICP备14008679号