c++编程实现: 1、设计和实现整型集合类(Set) 成员函数要求如下: l 添加构造函数完成初始化 l 能添加一个元素,元素不重复 l 能删除一个元素 l 输出所有元素 l 求两个集合对象的交集 l 求两个集合对象的并集 求两个集合对象的差集
时间: 2024-05-24 11:10:45 浏览: 32
#include <iostream>
#include <set>
using namespace std;
class Set {
private:
set<int> s;
public:
Set() {}
Set(int arr[], int n) {
for (int i = 0; i < n; i++) {
s.insert(arr[i]);
}
}
void add(int x) {
s.insert(x);
}
void remove(int x) {
s.erase(x);
}
void print() {
for (auto x : s) {
cout << x << " ";
}
cout << endl;
}
Set intersection(Set& a) {
Set res;
for (auto x : s) {
if (a.s.count(x)) {
res.add(x);
}
}
return res;
}
Set unionSet(Set& a) {
Set res(a.s.begin(), a.s.end());
for (auto x : s) {
res.add(x);
}
return res;
}
Set difference(Set& a) {
Set res;
for (auto x : s) {
if (!a.s.count(x)) {
res.add(x);
}
}
return res;
}
};
int main() {
int arr1[] = { 1, 2, 3 };
int arr2[] = { 2, 3, 4 };
Set a(arr1, 3);
Set b(arr2, 3);
a.add(4);
a.remove(1);
a.print();
b.print();
Set c = a.intersection(b);
c.print();
Set d = a.unionSet(b);
d.print();
Set e = a.difference(b);
e.print();
return 0;
}
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)