请设计实现集合类,元素类型为整型。该集合类支持集合元素增加、删除、查询;并支持集合并、交、差运算;利用你设计的集合类,实现本题要求。程序应体现面向对象程序设计思想,结构合理。为保证结果唯一,集合元素递增排列。本题集合内元素可使用数组保存,假设集合元素个数不超100个
时间: 2024-02-17 20:02:25 浏览: 64
下面是一个简单的集合类的实现,元素类型为整型。该集合类支持集合元素增加、删除、查询;并支持集合并、交、差运算。
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
const int MAXSIZE = 100;
class Set {
private:
int data[MAXSIZE];
int size;
public:
Set() { size = 0; }
Set(int arr[], int n);
void insert(int x);
void remove(int x);
bool contains(int x) const;
void display() const;
Set unionSet(const Set& other) const;
Set intersection(const Set& other) const;
Set difference(const Set& other) const;
};
Set::Set(int arr[], int n) {
sort(arr, arr + n);
size = unique(arr, arr + n) - arr;
copy(arr, arr + size, data);
}
void Set::insert(int x) {
if (size >= MAXSIZE) {
cout << "Set is full!" << endl;
return;
}
if (contains(x)) return;
data[size++] = x;
sort(data, data + size);
}
void Set::remove(int x) {
int pos = find(data, data + size, x) - data;
if (pos == size) return;
for (int i = pos; i < size - 1; i++) {
data[i] = data[i + 1];
}
size--;
}
bool Set::contains(int x) const {
return find(data, data + size, x) != data + size;
}
void Set::display() const {
if (size == 0) {
cout << "Set is empty!" << endl;
return;
}
for (int i = 0; i < size; i++) {
cout << data[i] << " ";
}
cout << endl;
}
Set Set::unionSet(const Set& other) const {
Set res;
int i = 0, j = 0;
while (i < size && j < other.size) {
if (data[i] < other.data[j]) {
res.insert(data[i++]);
} else if (data[i] > other.data[j]) {
res.insert(other.data[j++]);
} else {
res.insert(data[i++]);
j++;
}
}
while (i < size) res.insert(data[i++]);
while (j < other.size) res.insert(other.data[j++]);
return res;
}
Set Set::intersection(const Set& other) const {
Set res;
int i = 0, j = 0;
while (i < size && j < other.size) {
if (data[i] < other.data[j]) {
i++;
} else if (data[i] > other.data[j]) {
j++;
} else {
res.insert(data[i++]);
j++;
}
}
return res;
}
Set Set::difference(const Set& other) const {
Set res;
int i = 0, j = 0;
while (i < size && j < other.size) {
if (data[i] < other.data[j]) {
res.insert(data[i++]);
} else if (data[i] > other.data[j]) {
j++;
} else {
i++;
j++;
}
}
while (i < size) res.insert(data[i++]);
return res;
}
int main() {
int a[] = {1, 2, 3, 4, 4, 5, 5, 6};
int b[] = {4, 5, 5, 6, 7, 8};
Set A(a, 8);
Set B(b, 6);
Set C = A.unionSet(B);
Set D = A.intersection(B);
Set E = A.difference(B);
C.display(); // Output: 1 2 3 4 5 6 7 8
D.display(); // Output: 4 5 6
E.display(); // Output: 1 2 3
return 0;
}
```
在这个实现中,我们使用一个数组来保存集合元素。在构造函数中,我们将输入数组排序并去重,以确保集合元素递增排列。集合的基本操作,如插入、删除和查询等,都比较简单。集合的并、交和差运算,可以根据集合元素的大小关系来实现。