unordered_set<int> uset
时间: 2024-06-09 17:06:46 浏览: 16
unordered_set是C++标准库中的一个容器,用于存储不重复的元素。它是基于哈希表实现的,因此插入、删除和查找操作的平均时间复杂度都是常数。
unordered_set可以存储任意类型的元素,比如int、string等。你可以使用unordered_set类模板来定义一个具体类型的unordered_set对象,如unordered_set<int> uset。
unordered_set的常用内置函数包括:
- insert:插入元素到unordered_set中。
- erase:删除unordered_set中的元素。
- find:查找unordered_set中是否存在指定的元素。
- size:返回unordered_set中元素的个数。
相关问题
unordered_set<int> set;
`unordered_set<int>`是C++11标准引入的一种集合类型,它是一个哈希表,内部元素无序,且不允许重复。在使用前,需要先包含相应的头文件`<unordered_set>`。在创建一个`unordered_set`对象时,可以指定模板参数,比如`int`表示集合中存储的元素的类型为整型。在定义变量时,需要使用与C++标准库容器相同的语法,如下所示:
```c++
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
unordered_set<int> set;
set.insert(5);
set.insert(3);
set.insert(8);
set.insert(1);
set.insert(1); // 重复元素将被忽略
for (int x : set) {
cout << x << " ";
}
return 0;
}
```
以上程序将输出`1 3 5 8`,其中5、3、8、1是集合中的元素,它们的顺序是不固定的,而重复的元素1只会被加入一次[^1]。
unordered_set<int>
unordered_set<int>是C++标准库中的一个容器类,用于存储不重复的整数集合。它使用哈希表来实现,因此插入、查找和删除的时间复杂度为常数。unordered_set<int>中的元素按照插入的顺序进行存储,并且不允许有重复的元素。
与unordered_multiset相比,unordered_set不允许有重复的元素,而unordered_multiset允许有重复的元素。因此,如果你需要存储不重复的元素,可以使用unordered_set<int>;如果你需要允许重复元素的集合,可以使用unordered_multiset。
下面是一个示例代码,展示了unordered_set<int>的基本用法:
```
#include <iostream>
#include <unordered_set>
int main() {
std::unordered_set<int> s;
// 插入元素
s.insert(1);
s.insert(-2);
s.insert(1);
s.insert(5);
s.insert(3);
// 遍历元素
for (auto it = s.begin(); it != s.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl; // 输出:1 -2 5 3
// 删除元素
s.erase(-2);
auto pos = s.find(5);
if (pos != s.end()) {
s.erase(pos);
}
// 交换集合
std::unordered_set<int> tmp{100, -200, 300, 250};
s.swap(tmp);
// 输出元素
for (auto e : s) {
std::cout << e << " ";
}
std::cout << std::endl; // 输出:100 300 -200 250
return 0;
}
```
在上述示例代码中,我们首先声明了一个unordered_set<int>对象s,并向其中插入了一些整数。然后,我们使用迭代器遍历unordered_set中的元素,并输出每个元素的值。接下来,我们删除了一些元素,并交换了集合s和tmp的内容。最后,我们输出了交换后的集合s中的元素。
总结来说,unordered_set<int>是一个无序不重复的整数集合容器,它提供了插入、查找和删除等操作,并且具有常数时间复杂度。你可以根据需要选择unordered_multiset或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_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)