用c++实现集合的运算操作,包括交集、并集、差集、幂集、任意m元子集
时间: 2023-07-04 09:10:19 浏览: 142
以下是用C++实现集合的运算操作的示例代码:
```c++
#include <iostream>
#include <set>
#include <cmath>
using namespace std;
// 打印集合
void printSet(const set<int>& s) {
cout << "{ ";
for (auto x : s) {
cout << x << " ";
}
cout << "}" << endl;
}
// 交集
set<int> intersection(const set<int>& s1, const set<int>& s2) {
set<int> result;
for (auto x : s1) {
if (s2.count(x)) {
result.insert(x);
}
}
return result;
}
// 并集
set<int> unionSet(const set<int>& s1, const set<int>& s2) {
set<int> result = s1;
result.insert(s2.begin(), s2.end());
return result;
}
// 差集
set<int> difference(const set<int>& s1, const set<int>& s2) {
set<int> result;
for (auto x : s1) {
if (!s2.count(x)) {
result.insert(x);
}
}
return result;
}
// 幂集
set<set<int>> powerSet(const set<int>& s) {
set<set<int>> result;
int n = s.size();
int pow_n = pow(2, n);
for (int i = 0; i < pow_n; i++) {
set<int> subset;
for (int j = 0; j < n; j++) {
if ((i >> j) & 1) {
subset.insert(*next(s.begin(), j));
}
}
result.insert(subset);
}
return result;
}
// m元子集
set<set<int>> mSubset(const set<int>& s, int m) {
set<set<int>> result;
if (m == 0) {
result.insert({});
return result;
}
if (m == s.size()) {
result.insert(s);
return result;
}
int x = *s.begin();
set<int> rest = difference(s, { x });
set<set<int>> subsetsWithoutX = mSubset(rest, m);
set<set<int>> subsetsWithX = mSubset(rest, m - 1);
for (auto subset : subsetsWithX) {
subset.insert(x);
result.insert(subset);
}
result.insert(subsetsWithoutX.begin(), subsetsWithoutX.end());
return result;
}
int main() {
set<int> s1 = { 1, 2, 3, 4 };
set<int> s2 = { 3, 4, 5, 6 };
cout << "s1 = ";
printSet(s1);
cout << "s2 = ";
printSet(s2);
cout << endl;
set<int> s3 = intersection(s1, s2);
cout << "s1 ∩ s2 = ";
printSet(s3);
set<int> s4 = unionSet(s1, s2);
cout << "s1 ∪ s2 = ";
printSet(s4);
set<int> s5 = difference(s1, s2);
cout << "s1 - s2 = ";
printSet(s5);
set<set<int>> s6 = powerSet(s1);
cout << "P(s1) = " << endl;
for (auto subset : s6) {
printSet(subset);
}
set<set<int>> s7 = mSubset(s1, 2);
cout << "2元子集 = " << endl;
for (auto subset : s7) {
printSet(subset);
}
return 0;
}
```
示例输出:
```
s1 = { 1 2 3 4 }
s2 = { 3 4 5 6 }
s1 ∩ s2 = { 3 4 }
s1 ∪ s2 = { 1 2 3 4 5 6 }
s1 - s2 = { 1 2 }
P(s1) =
{ }
{ 1 }
{ 1 2 }
{ 1 2 3 }
{ 1 2 3 4 }
{ 1 2 4 }
{ 1 3 }
{ 1 3 4 }
{ 1 4 }
{ 2 }
{ 2 3 }
{ 2 3 4 }
{ 2 4 }
{ 3 }
{ 3 4 }
{ 4 }
2元子集 =
{ 1 2 }
{ 1 3 }
{ 1 4 }
{ 2 3 }
{ 2 4 }
{ 3 4 }
```
阅读全文