Фильтрация элементов

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

bool isOdd(int i) {
    return i % 2 != 0;
}

bool isEven(int i) {
    return i % 2 == 0;
}

//copies the elements that pass the test, returns how many
size_t filter(const int source[], size_t count, int result[], bool (*test)(
                          int)) {
    size_t resultCount = 0;
    for (size_t i = 0; i < count; i++) {
        if (test(source[i])) {
            result[resultCount++] = source[i];
        }
    }
    return resultCount;
}

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

int numbers[] = {1, 2, 3, 4, 5};
size_t count = sizeof numbers / sizeof numbers[0];

//room for all the elements: the most the result can take
int odd[5];
size_t oddCount = filter(numbers, count, odd, isOdd);
//odd is {1, 3, 5}

int evens[5];
size_t evenCount = filter(numbers, count, evens, isEven);
//evens is {2, 4}

printArray("odd", odd, oddCount);
printArray("evens", evens, evenCount);