2014-12-03 18 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