set的使用:
#include<iostream> #include<set> #include<string> #include<iterator> #include<algorithm>//set_union() using namespace std; void main(){ string s1[3]={"aaa","bbb","ccc"}; string s2[3]={"bbb","ddd","eee"}; set<string> sa(s1,s1+3);//申明一个set集合,元素为数组s1 set<string> sb(s2,s2+3);//申明一个set集合,元素为数组s2 set<string> sc;//申明一个空set集合 cout<<"输出sa的元素:"; copy(sa.begin(),sa.end(),ostream_iterator<string>(cout," ")); cout<<"\n\n输出sb的元素:"; copy(sb.begin(),sb.end(),ostream_iterator<string>(cout," ")); cout<<"\n\n输出sa和sb的并集:"; set_union(sa.begin(),sa.end(),sb.begin(),sb.end(),ostream_iterator<string>(cout," ")); cout<<"\n\n输出sa和sb的交集:"; set_intersection(sa.begin(),sa.end(),sb.begin(),sb.end(),ostream_iterator<string>(cout," ")); cout<<"\n\n输出sa-sb:"; set_difference(sa.begin(),sa.end(),sb.begin(),sb.end(),ostream_iterator<string>(cout," ")); cout<<"\n\n输出sb-sa:"; set_difference(sb.begin(),sb.end(),sa.begin(),sa.end(),ostream_iterator<string>(cout," ")); set_union(sa.begin(),sa.end(),sb.begin(),sb.end(),insert_iterator<set<string>>(sc,sc.begin())); sc.insert("fff"); copy(sc.begin(),sc.end(),ostream_iterator<string>(cout," ")); cout<<endl; cout<<"\n输出处理后的sc:"; copy(sc.lower_bound("ddd"),sc.upper_bound("fff"),ostream_iterator<string>(cout," ")); cout<<endl<<endl; }
hash_set (在Dev C++ 和Linux记得加上 using namespace __gnu_cxx; ):
#include<iostream> #include<string> #include<iterator> #include<algorithm> #include<hash_set> #include<windows.h> using namespace std; void main(){ const int N= 3; int s1[N]={1,2,3}; int s2[N]={4,5,6}; hash_set<int>sa(s1,s1+N);//申明一个集合sa,元素为数组s1 hash_set<int>sb(s2,s2+N);//申明一个集合sb,元素为数组s2 hash_set<int> sc;//申明一个集合sc,为空集合 ostream_iterator<int> output(cout," "); cout<<"输出集合sa的元素:"; copy(sa.begin(),sa.end(),output); cout<<"\n\n输出集合sb的元素:"; copy(sb.begin(),sb.end(),output); cout<<endl; system("pause"); }