一.用法详细介绍
- #<unordered_set>头文件中包含了, unordered_set 和 unordered_multiset;
- #<unordered_map>头文件中包含了,unordered_map 和 unordered_multimap;
- set,multiset,map,multimap 都是用红黑树来实现的,插入、删除、查询效率都是O(logN),元素是进行排序的;
- unordered_set、unordered_multiset、unordered_map、unordered_multimap都是用哈希表实现的,查询效率是O(1), 元素是无序的;
- 采用哪一种stl关键看两个点:需不需要元素排序 需不需要元素重复
pair的头文件是#include<ultity>
可以和map经常配合使用,刷题时候注意一下并做记录
1.添加元素
hashset.insert(3); //如果3存在,则不会插入
//注意,无法通过对迭代器赋值改变集合中的值
2.删除元素
hashset.erase(元素值);
hashset.erase(元素的迭代器);
hashset.erase(元素的迭代器1,元素的迭代器2); //删除从[first,last)的元素
3.查找元素
hashset.find(2); //返回的是迭代器,如果没有则返回hashset.end()
hashset.count(2); //返回元素存在个数,没有返回0
二.例子(摘自力扣)
#include <unordered_set> // 0. include the library
#include<iostream>
using namespace std;
int main() {
// 1. initialize a hash set
unordered_set<int> hashset;
// 2. insert a new key
hashset.insert(3);
hashset.insert(2);
hashset.insert(1);
// 3. delete a key
hashset.erase(2);
// 4. check if the key is in the hash set
if (hashset.count(2) <= 0) {
cout << "Key 2 is not in the hash set." << endl;
}
// 5. get the size of the hash set
cout << "The size of hash set is: " << hashset.size() << endl;
// 6. iterate the hash set
for (auto it = hashset.begin(); it != hashset.end(); ++it) {
cout << (*it) << " ";
}
cout << "are in the hash set." << endl;
// 7. clear the hash set
hashset.clear();
// 8. check if the hash set is empty
if (hashset.empty()) {
cout << "hash set is empty now!" << endl;
}
}