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