用c++实现集合的运算操作,包括交集、并集、差集、幂集、任意m元子集
时间: 2023-07-04 10:10:19 浏览: 195
以下是 C++ 实现集合运算操作的代码:
```c++
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
// 交集
set<int> intersection(set<int> s1, set<int> s2) {
set<int> result;
set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(result, result.begin()));
return result;
}
// 并集
set<int> union_set(set<int> s1, set<int> s2) {
set<int> result;
set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(result, result.begin()));
return result;
}
// 差集
set<int> difference(set<int> s1, set<int> s2) {
set<int> result;
set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(result, result.begin()));
return result;
}
// 幂集
vector<set<int>> power_set(set<int> s) {
vector<set<int>> result;
int n = s.size();
for (int i = 0; i < (1 << n); i++) {
set<int> subset;
for (int j = 0; j < n; j++) {
if (i & (1 << j)) {
auto it = s.begin();
advance(it, j);
subset.insert(*it);
}
}
result.push_back(subset);
}
return result;
}
// 任意m元子集
vector<set<int>> m_subset(set<int> s, int m) {
vector<int> indices(s.size());
iota(indices.begin(), indices.end(), 0);
vector<set<int>> result;
vector<int> combination(m, 0);
int i = 0;
while (i >= 0) {
combination[i]++;
if (combination[i] > s.size() - indices.size() + i) {
i--;
}
else if (i == m - 1) {
set<int> subset;
for (int j = 0; j < m; j++) {
auto it = s.begin();
advance(it, indices[combination[j]]);
subset.insert(*it);
}
result.push_back(subset);
}
else {
i++;
indices[i] = indices[i - 1] + 1;
combination[i] = combination[i - 1];
}
}
return result;
}
int main() {
set<int> s1 = {1, 2, 3, 4};
set<int> s2 = {3, 4, 5, 6};
// 交集
set<int> intersection_set = intersection(s1, s2);
cout << "Intersection: ";
for (auto x: intersection_set) {
cout << x << " ";
}
cout << endl;
// 并集
set<int> union_set_ = union_set(s1, s2);
cout << "Union: ";
for (auto x: union_set_) {
cout << x << " ";
}
cout << endl;
// 差集
set<int> difference_set = difference(s1, s2);
cout << "Difference: ";
for (auto x: difference_set) {
cout << x << " ";
}
cout << endl;
// 幂集
vector<set<int>> power_set_ = power_set(s1);
cout << "Power set:" << endl;
for (auto subset: power_set_) {
for (auto x: subset) {
cout << x << " ";
}
cout << endl;
}
// 任意m元子集
vector<set<int>> m_subset_ = m_subset(s1, 3);
cout << "3-subset:" << endl;
for (auto subset: m_subset_) {
for (auto x: subset) {
cout << x << " ";
}
cout << endl;
}
return 0;
}
```
该代码使用 set 类型来表示集合,并使用 algorithm 库中的函数实现了交集、并集、差集的操作。幂集的实现使用了位运算,任意 m 元子集的实现使用了组合数学中的技巧。
阅读全文