设置什么?
集合是一个关联容器,其中包含一组排序的键类型的唯一对象。每个元素只能出现一次,因此不允许重复。用户可以通过以任何顺序插入元素来创建集合,集合将返回排序后的数据给用户,这意味着集合包含用于对从用户抽象的数据进行排序的定义。
可以使用set的主要原因是-
当排序的数据是必需的
当不需要重复值时,仅需要唯一数据
当我们要使用二进制搜索树而不是哈希表时。
如果有一个与搜索时间没有问题,因为它需要的log(n)的复杂性中搜索
输入-
set = {2, 1, 5, 6, 9, 3, 2}输出-
1, 2, 3, 5, 6, 9
注-值以随机顺序插入,但按集合排序,并且从集合中删除重复的值。
#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是含有一组无序随机插入的数据的关联的容器。每个元素只能出现一次,因此不允许重复。用户可以通过以任何顺序插入元素来创建无序集合,并且无序集合将以任何顺序(即无序形式)返回数据。
可以使用无序集合的主要原因是-
如果不需要排序的数据,则表示该数据以无序格式可用
当不需要重复值时,仅需要唯一数据
当我们要使用哈希表而不是二进制搜索树时。
当需要更快的搜索时,在平均情况下需要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