遍历set集合,输出所有元素,用空格隔开,末尾换行,用c++
时间: 2024-05-25 12:15:48 浏览: 54
C++ Set(集合)
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct _set {
int *data;
int size;
} Set;
Set *createSet(int size) {
Set *set = (Set *)malloc(sizeof(Set));
set->data = (int *)malloc(sizeof(int) * size);
set->size = size;
return set;
}
void insert(Set *set, int num) {
for (int i = 0; i < set->size; i++) {
if (set->data[i] == num) {
return;
}
if (set->data[i] == 0) {
set->data[i] = num;
return;
}
}
}
void traverse(Set *set) {
for (int i = 0; i < set->size; i++) {
if (set->data[i] != 0) {
printf("%d ", set->data[i]);
}
}
printf("\n");
}
int main() {
Set *set = createSet(10);
insert(set, 1);
insert(set, 2);
insert(set, 3);
insert(set, 4);
insert(set, 5);
traverse(set);
return 0;
}
阅读全文