输入任意两个集合,用c++实现集合的运算操作,包括交集、并集、差集、幂集、任意m元子集
时间: 2023-07-10 20:09:51 浏览: 254
c++程序设计实现集合交集并集差集.docx
以下是用 C++ 实现集合运算操作的示例代码:
```cpp
#include <iostream>
#include <set>
#include <cmath>
using namespace std;
// 定义集合类型为 set<int>
typedef set<int> Set;
// 打印集合元素
void printSet(Set s) {
cout << "{ ";
for (auto it = s.begin(); it != s.end(); it++) {
cout << *it << " ";
}
cout << "}" << endl;
}
// 计算集合交集
Set intersection(Set s1, Set s2) {
Set result;
for (auto it = s1.begin(); it != s1.end(); it++) {
if (s2.find(*it) != s2.end()) {
result.insert(*it);
}
}
return result;
}
// 计算集合并集
Set unionSet(Set s1, Set s2) {
Set result = s1;
for (auto it = s2.begin(); it != s2.end(); it++) {
result.insert(*it);
}
return result;
}
// 计算集合差集
Set difference(Set s1, Set s2) {
Set result;
for (auto it = s1.begin(); it != s1.end(); it++) {
if (s2.find(*it) == s2.end()) {
result.insert(*it);
}
}
return result;
}
// 计算集合幂集
Set powerSet(Set s) {
Set result;
int n = s.size();
int m = pow(2, n);
for (int i = 0; i < m; i++) {
Set subset;
int j = 0;
for (auto it = s.begin(); it != s.end(); it++) {
if (i & (1 << j)) {
subset.insert(*it);
}
j++;
}
result.insert(subset);
}
return result;
}
// 计算任意 m 元子集
Set mSubset(Set s, int m) {
Set result;
if (m == 0) {
result.insert(Set());
return result;
}
if (m > s.size()) {
return result;
}
int n = s.size();
vector<bool> mask(n, false);
for (int i = 0; i < m; i++) {
mask[i] = true;
}
do {
Set subset;
int j = 0;
for (auto it = s.begin(); it != s.end(); it++) {
if (mask[j]) {
subset.insert(*it);
}
j++;
}
result.insert(subset);
} while (prev_permutation(mask.begin(), mask.end()));
return result;
}
int main() {
Set s1 = {1, 2, 3, 4, 5};
Set s2 = {4, 5, 6, 7, 8};
cout << "s1: ";
printSet(s1);
cout << "s2: ";
printSet(s2);
Set s3 = intersection(s1, s2);
cout << "s1 ∩ s2: ";
printSet(s3);
Set s4 = unionSet(s1, s2);
cout << "s1 ∪ s2: ";
printSet(s4);
Set s5 = difference(s1, s2);
cout << "s1 - s2: ";
printSet(s5);
Set s6 = powerSet(s1);
cout << "P(s1):" << endl;
for (auto it = s6.begin(); it != s6.end(); it++) {
printSet(*it);
}
Set s7 = mSubset(s1, 3);
cout << "3元子集:" << endl;
for (auto it = s7.begin(); it != s7.end(); it++) {
printSet(*it);
}
return 0;
}
```
该代码实现了以下集合运算操作:
- 计算集合交集
- 计算集合并集
- 计算集合差集
- 计算集合幂集
- 计算任意 m 元子集
其中,集合类型为 `set<int>`,可以通过模板的方式替换为其他类型的集合。在输出集合时,使用了迭代器遍历集合元素。在计算幂集和任意 m 元子集时,使用了循环和位运算来生成子集。
阅读全文