2014-10-30 24 views
-3

對於類分配,我需要創建4個函數以在程序中進行測試。我必須使用copyArray函數,PrintArray函數和InputArray函數。我遇到的最大問題是copyArray部分。我自己完成了大部分代碼,但是我需要知道我是否接近解決方案或根本不關閉。我敢肯定,代碼是一團糟。如果有人能夠幫助我找到正確的方向,我將非常感激。使用C++複製,打印和輸入數組

#include <iostream> using std::cin; using std::cout; using std::endl; using std::istream; using std::ostream; void inputArray(istream &, int[], int*); void printArray(ostream &, const int[], int); float a[4] = { 0, 1, 2, 3 }; float b[4]; void copyArray(const int orig[], int dup[], int); void main() { int a[4] = { 7, 14, 9, 10 }; int b[4]; cout << "The input data : " << endl; inputArray(cin, a, b); cout << "The printArray data : " << endl; printArray(cout, b, 4); } //---------------------------------------------------------------------------- void inputArray(istream & in, int t[], int howMany) { for (int i = 0; i < howMany; i++) in >> t[i]; return; } //----------------------------------------------------------------------------- void printArray(ostream & out, const int r[], int cnt) { for (int i = 0; i< cnt; i++) out << r[i] << endl; return; } void copyArray(const int orig [], int dup [], int); for (int i = 0; i < 4; i++){ b[i] = a[i]; } }

+0

您對'inputArray'的聲明,定義和用法暗示了三種不同的東西。 – crashmstr 2014-10-30 19:17:43

+0

究竟是您使用此代碼時遇到的問題?我可以猜到,但這對你發現問題很有幫助。 – 2014-10-30 19:17:51

+0

編寫測試用例,瞭解您是否有正確的解決方案。 – 2014-10-30 19:18:22

回答

0

當然,這將是更好地界定功能copyArray爲模板功能。例如

template <typename T, size_t N> 
void copyArray(T (&dst)[N], const T (&src)[N]) 
{ 
    for (size_t i = 0; i < N; i++) dst[i] = src[i]; 
} 

至於你的函數聲明,然後其定義可以像

void copyArray(int dst[], const int src[], size_t n) 

    for (size_t i = 0; i < n; i++) dst[i] = src[i]; 
} 

在函數定義由你顯示你有右括號後的分號去掉,並使用函數參數,而不是的全局變量。

要考慮到有標準算法std::copystd::copy_nstd::copy_if,在報頭<algorithm>可以用於應對陣列聲明std::copy_backward