unordered set find
时间: 2023-12-10 16:31:44 浏览: 29
unordered_set 的 find 函数可以用来查找某个元素是否在集合中存在,其时间复杂度为 O(1)。
使用方法如下:
```c++
#include <unordered_set>
using namespace std;
int main() {
unordered_set<int> s = {1, 2, 3, 4, 5};
if (s.find(3) != s.end()) {
cout << "3 is in the set" << endl;
} else {
cout << "3 is not in the set" << endl;
}
return 0;
}
```
输出结果为:
```
3 is in the set
```
相关问题
unordered_set find
unordered_set的find函数用于在unordered_set容器中查找特定元素。它返回一个迭代器,指向查找到的元素,如果未找到,则返回指向unordered_set容器末尾的迭代器。
以下是使用unordered_set的find函数的示例代码:
```cpp
#include <iostream>
#include <unordered_set>
int main() {
std::unordered_set<int> mySet = {1, 2, 3, 4, 5};
auto it = mySet.find(3);
if (it != mySet.end()) {
std::cout << "Element found: " << *it << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
return 0;
}
```
输出结果:
```
Element found: 3
```
如果要检查unordered_set容器中是否存在某个元素,可以使用find函数来查找元素。如果返回的迭代器指向容器末尾,表示元素未找到。
unordered set
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的问题!如果还有其他问题,请随时提问。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)