unordered_set的find函数
时间: 2023-05-02 21:03:58 浏览: 67
unordered_set 的 find 函数是用来查找指定元素的函数。它的时间复杂度为 O(1),即平均情况下查找时间与集合中元素数量无关。如果能够成功找到元素,则返回该元素的迭代器;否则返回集合的 end 迭代器。
相关问题
unordered_set的函数
unordered_set是C++标准库中的一个容器,它是一个无序集合,内部元素没有特定的顺序。下面是一些unordered_set常用的函数:
1. insert(key):向unordered_set中插入一个元素key。
2. erase(key):从unordered_set中删除一个元素key。
3. find(key):查找unordered_set中是否存在元素key,并返回指向该元素的迭代器。如果不存在,则返回unordered_set::end()。
4. count(key):返回unordered_set中等于给定键key的元素的数量。由于unordered_set中每个键只能出现一次,因此返回值只能是0或1。
5. size():返回unordered_set中的元素数量。
6. empty():判断unordered_set是否为空。
7. clear():清空unordered_set中的所有元素。
8. begin()和end():返回指向unordered_set首个元素和尾后元素的迭代器,用于遍历unordered_set。
此外,unordered_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函数来查找元素。如果返回的迭代器指向容器末尾,表示元素未找到。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)