概念及常用操作
一般意义的集合和我们高中学习的集合基本是一样的,也就是具有无序性、确定性和唯一性。但在编程中也有有序的集合。
常用操作是求差集、补集、并集等等。
实现
常用语言的实现方式如下:
- C:自己根据原理手写一个
- C++:STL set (底层采用红黑树实现)
- Java:set
- Python:set
C++实现
#include <iostream>
#include <map>
#include <set>
using namespace std;
int main(){
set<int> s,s2;
s.insert(10);
s.insert(2);
s.insert(3);
for(auto it=s.begin();it!=s.end();it++)
cout<<*it<<" ";
cout<<endl;
for(auto x:s)
cout<<x<<" ";
cout<<endl;
// analyse the result, it is ordered. because set is finish by red-black tree(the tree is ordered)
s2.insert(5);
s2.insert(3);
for(auto x:s2)
cout<<x<<" ";
cout<<endl;
s.insert(s2.begin(),s2.end());
for(auto x:s)
cout<<x<<" ";
cout<<endl;
return 0;
}
//2 3 10
//2 3 10
//3 5
//2 3 5 10
//
//Process returned 0 (0x0) execution time : 0.090 s
//Press any key to continue.
Python实现
Python直接使用set就行。
s=set()
s.add(1)
s.add(2)
print(s)