C ++中的原始数组与数组模板

时间:2014-12-03 01:26:32

标签: c++ arrays templates primitive-types

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

// 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;
    }
}

2 个答案:

答案 0 :(得分:3)

使testArr成为原始数组:

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

或致电data()以获取基础数组:

if (sortSortedArray(testArr.data(), 3)) {

答案 1 :(得分:1)

#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);
}