Инициализация множеств

Массивы и коллекции / Множества

//C has no set: this is a sorted array without repeats,
//so a search is a binary search
typedef struct {
    int *items;
    size_t count;
} Set;

int compareInts(const void *a, const void *b) {
    int x = *(const int *)a;
    int y = *(const int *)b;
    return (x > y) - (x < y);
}

//a pointer to the element, or nullptr if there is no such element
int *setFind(const Set *s, int value) {
    return bsearch(&value, s->items, s->count, sizeof(int), compareInts);
}

//puts the value in its sorted place, a repeat is skipped
void setAdd(Set *s, int value) {
    if (setFind(s, value) != nullptr) {
        return;
    }
    s->items = realloc(s->items, (s->count + 1) * sizeof(int));
    size_t i = s->count;
    for (; i > 0 && s->items[i - 1] > value; i--) {
        s->items[i] = s->items[i - 1];
    }
    s->items[i] = value;
    s->count++;
}

void setPrint(const char *name, const Set *s) {
    printf("%s is {", name);
    for (size_t i = 0; i < s->count; i++) {
        if (i > 0) {
            printf(", ");
        }
        printf("%d", s->items[i]);
    }
    printf("}\n");
}

//empty set: {} sets items to nullptr and count to 0
Set empty = {};
//empty is {}

//init with some data: the order and the repeats do not matter
int values[] = {3, 1, 2, 3};
Set intSet = {};
for (size_t i = 0; i < sizeof values / sizeof values[0]; i++) {
    setAdd(&intSet, values[i]);
}
//intSet is {1, 2, 3}

setPrint("empty", &empty);
setPrint("intSet", &intSet);
free(intSet.items);