64,639
社区成员
发帖
与我相关
我的任务
分享
int arr[M][M];
arr = new int*[M];
for(int i = 0; i < M; ++i)
arr[i] = new int[M];
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
int** pArray = new int* [N];
pArray[0] = new int[N * N]; // 分配连续内存
// 用pArray[1][0]无法寻址,还需指定下标寻址方式
for(int i = 1; i < N; i++)
{
pArray[i] = pArray[i-1] + N;
}
return 0;
}
#include <iostream>
#include <cstdlib>
using namespace std;
template<typename T> class Array;
template<typename T> class ArrayBody
{
friend class Array<T>;
T * tpBody;
int iRows,iColumns, iCurrentRow;
ArrayBody(int iRsz, int iCsz)
{
tpBody = new T[iRsz * iCsz];
iRows = iRsz; iColumns = iCsz; iCurrentRow = -1;
}
public:
T& operator[](int j)
{
bool row_error, column_error;
row_error = column_error =false;
try
{
if (iCurrentRow < 0 || iCurrentRow >= iRows)
row_error = true;
if (row_error == true || column_error == true)
throw 'e';
}
catch(char)
{
if (row_error == true)
cerr << "行下标越界[" << iCurrentRow << "]";
if (column_error == true)
cerr << "列下标越界[" << j << "]";
cout << "\n";
}
return tpBody[iCurrentRow * iColumns + j];
}
~ArrayBody() { delete[] tpBody;}
};
template<typename T> class Array
{
ArrayBody<T> tBody;
public:
ArrayBody<T>& operator[](int i)
{
tBody.iCurrentRow = i;
return tBody;
}
Array(int iRsz, int iCsz):tBody(iRsz, iCsz){}
};
int main()
{
int row, col;
cout << "row:";
cin >> row;
cout << "col:";
cin >> col;
Array<int> a1(row, col);
int element;
for(int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cout << "array[" << i << "][" << j << "] = " ;
cin >> element;
a1[i][j] = element;
}
}
for(int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
element = a1[i][j];
cout << "array[" << i << "][" << j << "] = " <<element << "\t";
}
cout << endl;
}
system("PAUSE");
return 0;
}