chapter16_13_set.cpp
#include <iostream>
#include <string>
#include <set>
#include <algorithm>
#include <iterator>
int main(){
using namespace std;
const int N = 6;
string s1[N] = {"buffoon", "thinkers", "for", "heavy", "can", "for"}; //设置了两个字符串数组
string s2[N] = {"metal", "any", "food", "elegant", "deliver", "for"};
set<string> A(s1, s1 + N); //设置关联容器,并且按照从小到大的顺序进行排序
set<string> B(s2, s2 + N);
ostream_iterator<string, char> out(cout, " "); //定义输出迭代器,第一个模板参数为指向的数据类型,第二个模板参数为输出格式
//第一个类参数为输出流的指向,第二个类模板参数为每次输出一个数据后的间隔字符
cout << "Set A: ";
copy(A.begin(), A.end(), out); //copy函数拷贝关联容器A中的内容到输出流
cout << endl;
cout << "Set B: ";
copy(B.begin(), B.end(), out); //copy函数拷贝关联容器B中的内容输出
cout << endl;
cout << "Union of A and B:\n";
set_union(A.begin(), A.end(), B.begin(), B.end(), out); //A和B的并集
cout << endl;
cout << "Intersection of A and B:\n";
set_intersection(A.begin(), A.end(), B.begin(), B.end(), out); //A和B的交集
cout << endl;
cout << "Difference of A and B:\n";
set_difference(A.begin(), A.end(), B.begin(), B.end(), out); //A和B的差集
cout << endl;
set<string> C;
cout << "Set C:\n";
set_union(A.begin(), A.end(), B.begin(), B.end(), insert_iterator<set<string>>(C, C.begin())); //把A和B中的数据插入到关联容器C中
copy(C.begin(), C.end(), out);
cout << endl;
string s3("grungy");
C.insert(s3); //插入了s3这个元素,并且容器会自动对它排序,所以没必要设置插入位置
cout << "Set C after insertion:\n";
copy(C.begin(), C.end(), out);
cout << endl;
cout << "Showing a range:\n";
copy(C.lower_bound("ghost"), C.upper_bound("spook"), out); //g ≤ 值范围 <s
cout << endl;
return 0;
}