C++中的基元数组与数组模板

Primitive array vs. Array template in C++

本文关键字:数组 C++      更新时间:2023-10-16

我从破解编码面试书中得到了这个问题。我能够用python和java编写此方法。但是当我尝试用 c++ 编写它时,编译器开始对我大喊大叫。我认为问题在于,在主函数中,我有一个由模板实例化的数组,但该函数正在接受一个原始数组。我应该如何实例化基元数组?

// Given a sorted array of positive integers with an empty spot (zero) at the
// end, insert an element in sorted order. 
bool sortSortedArray(size_t arrInt[], size_t x)
{
    size_t indexArr{0};
    size_t insertNum{x};
    while (x != 0) {
        if (x < arrInt[indexArr]) {
            size_t swapVal = arrInt[indexArr];
            arrInt[indexArr];
            insertNum = swapVal;
            ++indexArr;
        }

    }
    return true;
}
// Test the sortSortedArray function.
int main()
{
    array<size_t, 5> testArr{1, 4, 5, 8, 0};
    if (sortSortedArray(testArr, 3)) {
        return 0;
    }
}

要么testArr做一个基元数组:

int testArr[] = {1, 4, 5, 8, 0};

或调用 data() 以获取底层数组:

if (sortSortedArray(testArr.data(), 3)) {
#include <cstddef>
#include <array>
#include <iostream>
// this is a function template because each std::array<> parameter set creates a
// a type and we need a function for each type (we know std::size_t is the element
// type so this is only parameterized on the size)
template<size_t ArrSize>
void sortSortedArray(
    std::array<std::size_t, ArrSize>& arr,
    const std::size_t insertNum)
{
    // last position is known to be "empty"
    arr[arr.size() - 1] = insertNum;
    // swap value in last position leftwards until value to the left is less
    auto pos = arr.size() - 1;
    if (pos == 0)
        return;
    while (arr[pos - 1] > arr[pos])
    {
        const auto tmp = arr[pos - 1];
        arr[pos - 1] = arr[pos];
        arr[pos] = tmp;
        --pos;
        if (pos == 0)
            return;
    }
}
template<typename T, size_t N>
void printArray(const std::array<T, N>& r)
{
    for (const auto i : r)
    {
        std::cout << i << " ";
    }
    std::cout << 'n';
}
int main()
{
    std::array<std::size_t, 5> testArr{{1, 4, 5, 8, 0}};
    printArray(testArr);
    sortSortedArray(testArr, 3);
    printArray(testArr);
}