2014-12-03 43 views
1

我從破解編碼面試書中得到了這個問題。我能夠用python和java編寫這個方法。但是當我試圖用C++編寫它時,編譯器開始對我大喊大叫。我認爲問題在於,在主函數中,我有一個由模板實例化的數組,但函數採用的是原始數組。我應該如何實例化一個基本數組?原始數組與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; 
    } 
} 
+0

'的std :: array'和內置陣列是完全獨立的類型。 – chris 2014-12-03 01:30:33

+0

一般而言,它要求的問題是用一種類型的參數定義一個函數,並用完全不同類型的參數來調用它。 – 2014-12-03 01:33:29

回答

3

要麼讓testArr基本數組:

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

或致電data()讓底層陣列:

if (sortSortedArray(testArr.data(), 3)) { 
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); 
} 
+0

謝謝!在準備面試時,我很忙。但當時它確實有幫助。 – Angelo 2014-12-28 05:49:46

+0

沒問題。如果這有幫助,你也可以接受這個答案,甚至可以upvote。 ;) – Praxeolitic 2014-12-31 14:29:56