哈希表
- C++关于哈希表有很多数据结构,使用较多的有unordered_set和unordered_map,其中unordered_map存储的是键值对,unordered_map存储的键值对。
- 哈希表一般可以用来快速判断一个元素是否出现在集合里。(这一点很重要)
遍历
unordered_map<int, int> hash;
hash.insert(std::make_pair(1, 1));
hash.insert(std::make_pair(2, 2));
for(auto i = hash.end(); i != hash.end(); i++)
{
cout << i->first << ":" << i->second;
}
查找
- 查找某个元素是否在哈希表中,可以使用 hash.find(x) != hash.end() 或者 hash.count(x) > 0
- hash.find(x)是一个在hash中查找指定键x的操作。返回值是一个迭代器,指向hash中键为x的元素如果x在hash中存在,返回值是指向该元素的迭代器;如果x在hash中不存在,返回值是指向hash末尾的迭代器hash.end()。
- hash.count(x)是一个判断x是否在hash中的操作。返回值是一个整数,如果x在hash中存在,返回值为1;如果x在hash中不存在,返回值为0。
插入
- 在unordere_map中插入元素,可以使用hash[key] = value
- 也可以使用hash.insert(make_pair(1,1))
删除
在unordered_map和unordered_set中删除元素,都用hash.erase(key)