Pass a STL Array of fixed size as a parameter to another function without declaring the size in the function signature or prototype

There are two ways of doing this. You can either pass in a pointer/reference to the array along with it’s size to the function.

#include <iostream>
#include <array>

void swap(int *arr, int a, int b) {
    auto t  = arr[a];
    arr[a] = arr[b];
    arr[b] = t;
}

int partition(int *arr, int low, int high) {
    swap(arr, high, (low + high) / 2);

    auto store = low;
    for (auto i = low; i < high; i++) {
        if (arr[i] <= arr[high])
            swap(arr, store++, i);
    }

    swap(arr, store, high);
    return store;
}

void quickSort(int *arr, int low, int high) {
    if (low <= high) {
        auto p = partition(arr, low, high);
        quickSort(arr, low, p - 1);
        quickSort(arr, p + 1, high);
    }
}

void display(int *arr, int size) {
    for (auto i = 0; i < size; i++)
        std::cout << *(arr + i) << " ";
    std::cout << std::endl;
}

int main() {
    std::array<int, 9> arr = {9, 6, 3, 8, 1, 5, 2, 4, 7};
    std::cout << "Before sorting ..." << std::endl;
    display(arr.data(), arr.size());

    quickSort(arr.data(), 0, arr.size() - 1);

    std::cout << "After sorting ..." << std::endl;
    display(arr.data(), arr.size());

    getchar();
}

But, this is not really convenient. Another way would be to hardcode the size of the array in the function prototype which is BAD code and we should try to create a generic function capable of handling array of any size.

So, we will use function templates. SmileNow, there is no need to pass in the size of the array at all!

#include <iostream>
#include <array>

template<size_t N>
void swap(std::array<int, N>& arr, int a, int b) {
    auto t  = arr[a];
    arr[a] = arr[b];
    arr[b] = t;
}

template<size_t N>
void quickSort(std::array<int, N>& arr, int low, int high) {
    if (low <= high) {
        auto p = partition(arr, low, high);
        quickSort(arr, low, p - 1);
        quickSort(arr, p + 1, high);
    }
}

template<size_t N>
int partition(std::array<int, N>& arr, int low, int high) {
    swap(arr, high, (low + high) / 2);

    auto store = low;
    for (auto i = low; i < high; i++) {
        if (arr[i] <= arr[high])
            swap(arr, store++, i);
    }

    swap(arr, store, high);
    return store;
}

template<size_t N>
void display(std::array<int, N> const& arr) {
    for (auto i = arr.begin(); i != arr.end(); i++)
        std::cout << *i << " ";
    std::cout << std::endl;
}

int main() {
    std::array<int, 9> arr = {9, 6, 3, 8, 1, 5, 2, 4, 7};
    std::cout << "Before sorting ..." << std::endl;
    display(arr);

    quickSort(arr, 0, arr.size() - 1);

    std::cout << "After sorting ..." << std::endl;
    display(arr);

    getchar();
}

leave your comment