C++ STL 中 set 和 unordered_set 的区别(3)
在本文中,让我们了解 C++ STL 中的 set 和 unordered_set 是什么,从而了解它们之间的区别。
什么是 set?
set 是一种关联容器,它包含一组按 Key 类型排序的唯一对象。每个元素只能出现一次,因此不允许重复。用户可以通过任何顺序插入元素来创建 set,而 set 会向用户返回排序后的数据,这意味着 set 包含用于排序数据的定义,这些定义对用户是抽象的。
使用 set 的主要原因是 −
当需要排序后的数据时
当不需要重复值,只需要唯一数据时
当我们想要使用二叉搜索树而不是哈希表时。
当搜索时间没有问题时,因为它在搜索中需要log(n) 的复杂度
输入 −
set = {2, 1, 5, 6, 9, 3, 2}输出 −
1, 2, 3, 5, 6, 9
注意 − 值以随机顺序插入,但它们按 set 排序,并且重复值也会从 set 中删除。
示例
#include <iostream>
#include <set>
using namespace std;
int main(){
//creating an array
int arr[] = {2, 1, 5, 6, 9, 3, 2};
int size = sizeof(arr)/ sizeof(arr[0]);
//declaring a set
set<int> SET;
//inserting elements from an array to set using insert()
for(int i = 0; i<size; i++){
SET.insert(arr[i]);
}
set<int>::iterator it;
cout<<"Values in set are: ";
for(it = SET.begin(); it != SET.end(); it++){
cout <<*it<<" ";
}
}输出
上面代码的输出将是 −
Values in set are: 1 2 3 5 6 9
什么是 unordered_set?
unordered_set 是一种关联容器,它包含一组以随机方式插入的无序数据。每个元素只能出现一次,因此不允许重复。用户可以通过任何顺序插入元素来创建 unordered_set,并且 unordered_set 将以任何顺序(即无序形式)返回数据。
使用 unordered_set 的主要原因是 −
当不需要排序数据时,这意味着数据以无序格式提供
当不需要重复值,只需要唯一数据时
当我们想要使用哈希表而不是二叉搜索树时。
当需要更快的搜索时,因为它在平均情况下需要 O(1) 的时间复杂度,而在最坏情况下需要 O(n) 的时间复杂度
输入 −
set = {2, 1, 5, 6, 9, 3, 2}输出 −
3, 9, 6, 5, 2
示例
#include <iostream>
#include <unordered_set>
using namespace std;
int main (){
int arr[] = { 2, 1, 5, 6, 9, 3, 2 };
int size = sizeof (arr) / sizeof (arr[0]);
unordered_set < int >U_SET;
//inserting elements from an array to an unordered_set using insert()
for (int i = 0; i < size; i++){
U_SET.insert (arr[i]);
}
unordered_set < int >::iterator it;
cout << "Values in unordred set are: ";
for (it = U_SET.begin (); it != U_SET.end (); it++){
cout << *it << " ";
}
}输出
上面代码的输出将是 −
Values in unordered set are: 3 6 5 9 2 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP