c语言实现集合的并交差
时间: 2024-05-13 09:15:52 浏览: 45
c语言实现集合并交差
3星 · 编辑精心推荐
要实现集合的并、交、差操作,可以使用数组来表示集合,数组的元素表示集合中的元素,数组的长度表示集合的大小。以下是C语言实现集合的并、交、差操作的示例代码:
```c
#include <stdio.h>
// 求两个集合的并集
void union_set(int set1[], int size1, int set2[], int size2, int result[])
{
int i, j, k = 0;
for (i = 0; i < size1; i++) {
result[k++] = set1[i];
}
for (j = 0; j < size2; j++) {
int flag = 1;
for (i = 0; i < size1; i++) {
if (set2[j] == set1[i]) {
flag = 0;
break;
}
}
if (flag) {
result[k++] = set2[j];
}
}
}
// 求两个集合的交集
void intersect_set(int set1[], int size1, int set2[], int size2, int result[])
{
int i, j, k = 0;
for (i = 0; i < size1; i++) {
for (j = 0; j < size2; j++) {
if (set1[i] == set2[j]) {
result[k++] = set1[i];
break;
}
}
}
}
// 求两个集合的差集(set1 - set2)
void diff_set(int set1[], int size1, int set2[], int size2, int result[])
{
int i, j, k = 0;
for (i = 0; i < size1; i++) {
int flag = 1;
for (j = 0; j < size2; j++) {
if (set1[i] == set2[j]) {
flag = 0;
break;
}
}
if (flag) {
result[k++] = set1[i];
}
}
}
int main()
{
int set1[] = {1, 2, 3, 4, 5};
int set2[] = {4, 5, 6, 7, 8};
int size1 = sizeof(set1) / sizeof(int);
int size2 = sizeof(set2) / sizeof(int);
int result[10];
// 求并集
union_set(set1, size1, set2, size2, result);
printf("Set1 union Set2: ");
for (int i = 0; i < size1 + size2; i++) {
printf("%d ", result[i]);
}
printf("\n");
// 求交集
intersect_set(set1, size1, set2, size2, result);
printf("Set1 intersect Set2: ");
for (int i = 0; i < size1 + size2; i++) {
printf("%d ", result[i]);
}
printf("\n");
// 求差集
diff_set(set1, size1, set2, size2, result);
printf("Set1 diff Set2: ");
for (int i = 0; i < size1 + size2; i++) {
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
```
输出结果为:
```
Set1 union Set2: 1 2 3 4 5 6 7 8
Set1 intersect Set2: 4 5
Set1 diff Set2: 1 2 3
```
注意,上面的实现是基于数组的,如果集合元素较多,可能会占用大量的内存。对于大规模的集合操作,可以考虑使用其他数据结构,如哈希表等。
阅读全文