C语言//补充代码,求并集、交集、差集
时间: 2024-09-22 19:07:39 浏览: 43
链表的交集并集差集c语言.cpp
在C语言中,由于标准库并不直接提供集合操作的函数,我们可以使用数组或者结构体来模拟集合,并通过自定义函数来实现并集、交集和差集的操作。这里是一个简单的示例,假设我们有一个`set`数据结构,包含整数元素:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Set {
int *array; // 存储元素的数组
size_t size;
size_t capacity;
} Set;
// 动态分配内存,初始化集合
Set* create_set(size_t capacity) {
Set *s = (Set*)malloc(sizeof(Set));
s->array = (int*)malloc(capacity * sizeof(int));
s->size = 0;
s->capacity = capacity;
return s;
}
// 插入元素
void insert(Set *s, int element) {
if (s->size == s->capacity) {
s->capacity *= 2;
s->array = (int*)realloc(s->array, s->capacity * sizeof(int));
}
s->array[s->size++] = element;
}
// 检查元素是否存在
int is_member(const Set *s, int element) {
for (size_t i = 0; i < s->size; i++) {
if (s->array[i] == element)
return 1;
}
return 0;
}
// 并集
Set* union_set(Set *a, Set *b) {
Set *union_set = create_set(a->capacity + b->capacity);
for (int i = 0; i < a->size; i++)
insert(union_set, a->array[i]);
for (int i = 0; i < b->size; i++)
insert(union_set, b->array[i]);
free(a);
free(b);
return union_set;
}
// 交集
Set* intersection(Set *a, Set *b) {
Set *intersection = create_set(0); // 初始化空集
for (int i = 0; i < a->size && i < b->size; i++) {
if (is_member(b, a->array[i])) {
insert(intersection, a->array[i]);
}
}
free(a);
free(b);
return intersection;
}
// 差集(从A中减去B)
Set* difference(Set *a, Set *b) {
Set *difference = create_set(a->size);
for (int i = 0; i < a->size; i++) {
if (!is_member(b, a->array[i]))
insert(difference, a->array[i]);
}
free(a);
free(b);
return difference;
}
// 打印集合
void print_set(const Set *s) {
for (size_t i = 0; i < s->size; i++) {
printf("%d ", s->array[i]);
}
printf("\n");
}
// 示例
int main() {
Set *setA = create_set(5);
insert(setA, 1);
insert(setA, 2);
insert(setA, 3);
Set *setB = create_set(4);
insert(setB, 2);
insert(setB, 4);
insert(setB, 5);
Set *unionResult = union_set(setA, setB);
print_set(unionResult);
Set *intersectionResult = intersection(setA, setB);
print_set(intersectionResult);
Set *differenceResult = difference(setA, setB);
print_set(differenceResult);
free(setA);
free(setB);
free(unionResult);
free(intersectionResult);
free(differenceResult);
return 0;
}
```
请注意,这个示例非常基础且效率不高,实际应用中可能会选择更高效的数据结构如哈希表(如`std::unordered_set`)。此外,上述代码没有处理一些特殊情况,比如溢出等问题,生产环境中需要根据需求做适当的错误检查和处理。
阅读全文