unordered set
时间: 2023-11-10 15:06:31 浏览: 49
unordered_set是C++中的一个容器,它提供了一种存储唯一元素的方式,且元素的顺序是不确定的。unordered_set的实现基于哈希表,这使得插入、查找和删除操作的平均时间复杂度为常数时间O(1)。
使用unordered_set时,需要包含头文件<unordered_set>。下面是一个简单的示例代码,展示了unordered_set的基本用法:
```cpp
#include <iostream>
#include <unordered_set>
int main() {
// 创建一个unordered_set
std::unordered_set<int> mySet;
// 插入元素
mySet.insert(1);
mySet.insert(2);
mySet.insert(3);
// 遍历并打印unordered_set中的元素
for (const auto& element : mySet) {
std::cout << element << " ";
}
std::cout << std::endl;
// 查找元素
if (mySet.find(2) != mySet.end()) {
std::cout << "2 is found in the unordered_set." << std::endl;
} else {
std::cout << "2 is not found in the unordered_set." << std::endl;
}
// 删除元素
mySet.erase(1);
// 打印删除后的unordered_set
for (const auto& element : mySet) {
std::cout << element << " ";
}
std::cout << std::endl;
return 0;
}
```
输出结果:
```
3 2 1
2 is found in the unordered_set.
3 2
```
在上述示例中,我们创建了一个unordered_set,并插入了一些元素。然后我们遍历打印了unordered_set中的元素。接着,我们使用find函数查找了一个元素,并根据查找结果输出相应的信息。最后,我们删除了一个元素,并再次打印unordered_set中的元素。
希望这能解答你关于unordered_set的问题!如果还有其他问题,请随时提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)