怎样才能定义一个动态的数组?
大一新生 C自习到数组了 线代刚好上到 矩阵 突发奇想 用C的数组解矩阵 算法上有那么点想法 但是 却感觉无从下手
书上写了数组 不能动态定义 这让我很郁闷 不知道高手是怎么解决这个问题的
如果已经有写好的代码 发来 让我参考 参考 我也会不胜感激的!!
程序代码:#include <iostream>
#include <cstring>
using namespace std;
class NullPointerException {};
class MemoryException {};
class ArrayIndexOutOfBoundsException {};
class Array {
int rows;
int cols;
int *pArray;
public:
Array() : rows(0), cols(0), pArray(0) {}
Array(int r, int c) : rows(r), cols(c)
{
pArray = new int[r * c];
if (!pArray)
throw MemoryException();
memset(pArray, 0, sizeof(int) * r * c);
}
virtual void modify(int r, int c)
{
if (pArray)
delete []pArray;
pArray = new int[r * c];
if (!pArray)
throw MemoryException();
memset(pArray, 0, sizeof(int) * r * c);
}
virtual ~Array() {
if (pArray)
delete []pArray;
}
virtual void set(int x, int y, int value)
{
if (!pArray)
throw NullPointerException();
if (x < 0 || y < 0 || x >= rows || y >= rows)
throw ArrayIndexOutOfBoundsException();
*(pArray + (x * cols + y)) = value;
}
virtual int get(int x, int y)
{
if (!pArray)
throw NullPointerException();
if (x < 0 || y < 0 || x >= rows || y >= cols)
throw ArrayIndexOutOfBoundsException();
return *(pArray + (x * cols + y));
}
};
int main()
{
Array a(5, 5);
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
a.set(i, j, i * 5 + j);
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
cout << "a.get(" << i << ", " << j << ") = " << a.get(i, j) << endl;
}
这样可以不?
