原文 (3)定义一个集合类Set,最多存放100个不重复的整数,实现集合的如下操作: 1)增加某个整型元素时,保证集合中没有重复元素;删除指定的元素,查找该元素在集合中则从集合中删除该元素; 2)重载运算符“+”,实现两个集合对象的合并操作,重载运算符“*”,求两个集合对象的交集;例如Set s, s1, s2; s=sl+s2; s=s1* s2; 3)重载赋值运算符=和复合赋值运算符-=,实现两个集合对象的赋值操作与差集操作。 例如Sets1, s2; s1=s2; s1-=s2;集合S1中去掉S2中存在的元素。
时间: 2023-05-12 10:05:37 浏览: 144
可以的,以下是一个实现上述要求的 Set 类的代码:
```cpp
#include <iostream>
#include <algorithm>
class Set {
public:
Set() : size(0) {}
bool add(int x) {
if (size >= 100) return false;
if (contains(x)) return false;
data[size++] = x;
return true;
}
bool remove(int x) {
int i = indexOf(x);
if (i == -1) return false;
data[i] = data[--size];
return true;
}
bool contains(int x) const {
return indexOf(x) != -1;
}
Set operator+(const Set& other) const {
Set result;
for (int i = 0; i < size; ++i) {
result.add(data[i]);
}
for (int i = 0; i < other.size; ++i) {
result.add(other.data[i]);
}
return result;
}
Set operator*(const Set& other) const {
Set result;
for (int i = 0; i < size; ++i) {
if (other.contains(data[i])) {
result.add(data[i]);
}
}
return result;
}
Set& operator=(const Set& other) {
size = 0;
for (int i = 0; i < other.size; ++i) {
add(other.data[i]);
}
return *this;
}
Set& operator-=(const Set& other) {
for (int i = 0; i < other.size; ++i) {
remove(other.data[i]);
}
return *this;
}
private:
int indexOf(int x) const {
for (int i = 0; i < size; ++i) {
if (data[i] == x) {
return i;
}
}
return -1;
}
int data[100];
int size;
};
int main() {
Set s1, s2;
s1.add(1);
s1.add(2);
s1.add(3);
s2.add(2);
s2.add(3);
s2.add(4);
Set s = s1 + s2;
std::cout << "s = ";
for (int i = 0; i < s.size; ++i) {
std::cout << s.data[i] << " ";
}
std::cout << std::endl;
Set s3 = s1 * s2;
std::cout << "s3 = ";
for (int i = 0; i < s3.size; ++i) {
std::cout << s3.data[i] << " ";
}
std::cout << std::endl;
s1 = s2;
std::cout << "s1 = ";
for (int i = 0; i < s1.size; ++i) {
std::cout << s1.data[i] << " ";
}
std::cout << std::endl;
s1 -= s2;
std::cout << "s1 = ";
for (int i = 0; i < s1.size; ++i) {
std::cout << s1.data[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
对于 "lua closure factory 完整代码" 和 "中文加密" 的问题,我需要更多的信息才能回答。
阅读全文