c++中unordered_set的使用方法
时间: 2023-12-10 10:31:45 浏览: 35
unordered_set是C++ STL中的一个容器,它是一个无序的集合,其中的元素是唯一的。unordered_set的使用方法如下:
1. 头文件引入
```c++
#include <unordered_set>
```
2. 定义unordered_set
```c++
std::unordered_set<int> mySet;
```
3. 插入元素
```c++
mySet.insert(1);
mySet.insert(2);
mySet.insert(3);
```
4. 遍历元素
```c++
for (auto it = mySet.begin(); it != mySet.end(); ++it) {
std::cout << *it << " ";
}
```
5. 查找元素
```c++
if (mySet.find(2) != mySet.end()) {
std::cout << "Found" << std::endl;
} else {
std::cout << "Not found" << std::endl;}
```
6. 删除元素
```c++
mySet.erase(2);
```
相关问题
c++中的unordered_set的方法
unordered_set是C++标准库中的一个容器,它提供了一种无序、唯一元素的集合。下面是unordered_set的一些常用方法:
1. 插入元素:可以使用insert()方法将元素插入到unordered_set中,例如:
```
unordered_set<int> mySet;
mySet.insert(10);
```
2. 删除元素:可以使用erase()方法删除unordered_set中的元素,例如:
```
unordered_set<int> mySet;
mySet.erase(10);
```
3. 查找元素:可以使用find()方法查找unordered_set中的元素,如果找到了则返回指向该元素的迭代器,否则返回end()迭代器,例如:
```
unordered_set<int> mySet;
auto it = mySet.find(10);
if (it != mySet.end()) {
// 找到了元素
} else {
// 没有找到元素
}
```
4. 获取元素数量:可以使用size()方法获取unordered_set中元素的数量,例如:
```
unordered_set<int> mySet;
int count = mySet.size();
```
5. 遍历元素:可以使用迭代器来遍历unordered_set中的元素,例如:
```
unordered_set<int> mySet;
for (auto it = mySet.begin(); it != mySet.end(); ++it) {
// 使用*it访问当前元素
}
```
c++中unordered_set的count
在C++中,unordered_set是一种无序容器,用于存储唯一的元素。count()函数也适用于unordered_set,用于计算容器中特定元素的数量。它接受一个参数,即要计算数量的元素,并返回该元素在unordered_set中出现的次数。如果元素不存在,则返回0。以下是一个示例:
```cpp
#include <iostream>
#include <unordered_set>
int main() {
std::unordered_set<int> mySet = {1, 2, 3, 4, 5};
int element = 3; int count = mySet.count(element);
std::cout << "The count of " << element << " in the unordered_set is: " << count << std::endl;
return 0;
}
```
输出结果为:
```
The count of 3 in the unordered_set is: 1
```
在这个示例中,我们创建了一个包含整数的unordered_set,并使用count()函数计算元素3在unordered_set中的数量。因为元素3存在于unordered_set中,所以count的值为1。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)