#include <iostream>
#include <set>
#include <iterator>
#include <algorithm>
int main()
{
const int SIZE = 4;
std::string str1[SIZE] = {"zy", "yyt", "yyk", "yyj"};
std::string str2[SIZE] = {"ljq", "zy", "yyt", "others"};
//集合在定义时经过排序
std::set<std::string> set_a(str1, str1 + SIZE);
std::set<std::string> set_b(str2, str2 + SIZE);
std::ostream_iterator<std::string, char> std_out(std::cout, " ");
std::copy(set_a.begin(), set_a.end(), std_out);
std::cout << std::endl;
std::copy(set_b.begin(), set_b.end(), std_out);
std::cout << std::endl;
//取并集,然后传到标准输出流显示
std::set_union(set_a.begin(), set_a.end(), set_b.begin(), set_b.end(), std_out);
std::cout << std::endl;
//取交集,然后传到输出流显示
std::set_intersection(set_a.begin(), set_a.end(), set_b.begin(), set_b.end(), std_out);
std::cout << std::endl;
//求两集合之差,然后传到输出流显示
std::set_difference(set_a.begin(), set_a.end(), set_b.begin(), set_b.end(), std_out);
std::cout << std::endl;
std::set<std::string> set_c;
//将集合 set_a 和集合 set_b 取交集,然后插入到集合set_c中(不能直接复制)
std::set_union(set_a.begin(), set_a.end(), set_b.begin(), set_b.end(),
std::insert_iterator<std::set<std::string> >(set_c, set_c.begin()));
std::copy(set_c.begin(), set_c.end(), std_out);
std::cout << std::endl;
//插入一个字符串
set_c.insert("inserted_string");
std::copy(set_c.begin(), set_c.end(), std_out);
std::cout << std::endl;
//插入一个集合的内容
std::set<std::string> set_d = {"string1", "string2", "string3"};
set_c.insert(set_d.begin(), set_d.end());
std::copy(set_c.begin(), set_c.end(), std_out);
std::cout << std::endl;
//lower_bound()将键作为参数并返回一个迭代器,该迭代器指向集合中第一个不小于建参数的元素
//upper_bound()将键最为参数并返回一个迭代器,该迭代器指向集合中第一个大于键参数的元素
std::copy(set_c.lower_bound("string1"), set_c.upper_bound("string3"), std_out);
std::cout << std::endl;
//可反转显示
std::copy(set_c.rbegin(), set_c.rend(), std_out);
return 0;
}
集合set
最新推荐文章于 2024-05-15 12:50:53 发布