是C++ STL中的一种关联容器,它可以存储一组不重复的元素,并支持快速查找、插入和删除操作,时间复杂度均为O(1)。
unordered_set容器的实现方式是哈希表,即将元素映射到哈希表中的某个位置上,通过哈希函数来计算元素的哈希值,将哈希值映射到哈希表中的位置上,从而实现快速查找、插入和删除操作。
unordered_set容器的特点:
1. 无序:元素没有固定的顺序,插入顺序与元素在容器中的位置无关。
2. 不重复:容器中的元素是唯一的,相同的元素只会被存储一次。
3. 快速:查找、插入和删除操作的时间复杂度均为O(1),具有很高的效率。
unordered_set容器的常用操作:
1. 插入元素:使用insert()函数将元素插入到容器中。
2. 删除元素:使用erase()函数删除指定的元素。
3. 查找元素:使用find()函数查找指定的元素,如果找到了则返回指向该元素的迭代器,否则返回end()迭代器。
4. 遍历元素:使用迭代器可以遍历容器中的所有元素。
unordered_set容器的代码实现:```
#include <iostream>
#include <unordered_set>
using namespace std;
int main()
{
// 创建unordered_set容器
unordered_set<int> uset;
// 插入元素
uset.insert(1);
uset.insert(2);
uset.insert(3);
// 遍历容器中的元素
for (auto it = uset.begin(); it != uset.end(); ++it) {
cout << *it << " ";
}
cout << endl;
// 查找元素
auto it = uset.find(2);
if (it != uset.end()) {
cout << "Found: " << *it << endl;
} else {
cout << "Not found." << endl;
}
// 删除元素
uset.erase(3);
// 遍历容器中的元素
for (auto it = uset.begin(); it != uset.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
3 2 1
Found: 2
2 1
```
可以看到,unordered_set容器中的元素没有固定的顺序,插入顺序与元素在容器中的位置无关。使用find()函数可以查找指定的元素,如果找到了则返回指向该元素的迭代器,否则返回end()迭代器。使用erase()函数可以删除指定的元素。使用迭代器可以遍历容器中的所有元素。