4.关联式容器-set
·
前面几个小节介绍了序列式容器,接下来介绍第一个关联式容器集合set。集合set类似数学上面的集合概念但有所区别就是multiset多值集合允许集合里面有重复的元素且是有序的。
基本方法:
//单个集合操作
insert(); //插入某个元素
count(); //统计集合里面元素个数
find(); //查找某个元素
......
------------------------------------------
//多个集合操作
set_union(); //并集
set_intersection(); //交集
set_difference(); //差集
set_symmetric_difference(); //对称差集
接着重点介绍下集合的交、并、差和对称差集,以多值集合S1和S2为例。
S1 = {1,3,5,7,9,11};S2 = {1,1,2,3,5,8,13};

结果示意图:

可运行代码:
//
// Created by wsk on 25-10-24.
//
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
int main()
{
int a1[6] = {1,3,5,7,9,11};
int a2[7] = {1,1,2,3,5,8,13};
multiset<int> s1(a1,a1+6);
multiset<int> s2(a2,a2+7);
auto it1 = s1.begin();
cout << "s1: ";
while (it1 != s1.end())
{
cout << *it1 << " " ;
++it1;
}
cout << endl;
auto it2 = s2.begin();
cout << "s2: ";
while (it2 != s2.end())
{
cout << *it2 << " " ;
++it2;
}
cout << endl;
auto first1 = s1.begin();
auto last1 = s1.end();
auto first2 = s2.begin();
auto last2 = s2.end();
// 1.并集
cout << "s1 ∪ S2: ";
set_union(first1, last1, first2, last2, ostream_iterator<int>(cout, " "));
cout << endl;
// 2.交集
cout << "s1 ∩ S2: ";
set_intersection(first1, last1, first2, last2, ostream_iterator<int>(cout, " "));
cout << endl;
// 3.差集
cout << "s1 - S2: ";
set_difference(first1, last1, first2, last2, ostream_iterator<int>(cout, " "));
cout << endl;
cout << "s2 - S1: ";
set_difference(first2, last2, first1, last1, ostream_iterator<int>(cout, " "));
cout << endl;
// 4.对称差集s1 ⊕ S2 = (s1 - S2) ∪ (s2 - S1)
cout << "s1 ⊕ S2: ";
set_symmetric_difference(first1, last1, first2, last2, ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
更多推荐
所有评论(0)