2014-10-30 23 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