c++实现用类设计集合:存储有限的集合(简称有界集合类),数据不允许存储,会存满,实现集合的添加,判满,判空,是否存在,清空,排序,存储到文件,从文件读取。
时间: 2023-05-20 17:05:06 浏览: 52
好的,这是一个关于有界集合类的问题。下面是一个简单的 C++ 类实现,可以实现添加元素、判满、判空、查找元素、清空集合、排序集合、存储到文件和从文件读取等功能:
```cpp
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
const int MAX_SIZE = 100; // 集合的最大容量
class BoundedSet {
private:
int data[MAX_SIZE]; // 集合元素数组
int size; // 集合当前大小
public:
BoundedSet() { size = 0; } // 构造函数
bool isFull() { return size == MAX_SIZE; } // 判满
bool isEmpty() { return size == 0; } // 判空
bool contains(int x) { // 查找元素
for (int i = 0; i < size; i++) {
if (data[i] == x) return true;
}
return false;
}
void add(int x) { // 添加元素
if (size < MAX_SIZE) {
data[size++] = x;
}
}
void clear() { size = 0; } // 清空集合
void sort() { // 排序集合
std::sort(data, data + size);
}
void saveToFile(const char* filename) { // 存储到文件
ofstream fout(filename);
for (int i = 0; i < size; i++) {
fout << data[i] << " ";
}
fout.close();
}
void loadFromFile(const char* filename) { // 从文件读取
ifstream fin(filename);
clear();
int x;
while (fin >> x) {
add(x);
}
fin.close();
}
};
```
这个类实现了所有要求的功能,你可以根据需要进行调用。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)