1. 程式人生 > >C++ 二維陣列動態記憶體分配過載以及拷貝構造

C++ 二維陣列動態記憶體分配過載以及拷貝構造

總時間限制: 

1000ms

 

記憶體限制: 

65536kB

// 在此處補充你的程式碼

描述

寫一個二維陣列類 Array2,使得下面程式的輸出結果是:

0,1,2,3,

4,5,6,7,

8,9,10,11,

next

0,1,2,3,

4,5,6,7,

8,9,10,11,

程式:

#include <iostream>
#include <cstring>
using namespace std;

class Array2 {
};

int main() {
    Array2 a(3,4);
    int i,j;
    for(  i = 0;i < 3; ++i )
        for(  j = 0; j < 4; j ++ )
            a[i][j] = i * 4 + j;
    for(  i = 0;i < 3; ++i ) {
        for(  j = 0; j < 4; j ++ ) {
            cout << a(i,j) << ",";
        }
        cout << endl;
    }
    cout << "next" << endl;
    Array2 b;     b = a;
    for(  i = 0;i < 3; ++i ) {
        for(  j = 0; j < 4; j ++ ) {
            cout << b[i][j] << ",";
        }
        cout << endl;
    }
    return 0;
}

輸入

輸出

0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,

樣例輸入

None

樣例輸出

0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,

標準的動態記憶體分配,用一維陣列一級指標來表示二維陣列

#include <iostream>
#include <cstring>
using namespace std;

class Array2 {
	// 在此處補充你的程式碼
private:
	int *p;
	int row;
	int col;
public:
	Array2(int row_, int col_) :row(row_),col(col_)
	{
		p = new int[row*col+1];
	}

	int * operator [](int n)
	{
		return  p + n * col;
	}

	int operator()(int row_, int col_)
	{
		return *(p + row_ * col + col_);
	}
	Array2():row(0),col(0)
	{
		p = NULL;
	}

	Array2(Array2 &a)
	{
		if (p)
			delete[] p;
		p = new int[a.col*a.row + 1];
		col = a.col;
		row = a.row;
		memcpy(p, a.p, col*row);
	}
};

int main() {
	Array2 a(3, 4);
	int i, j;
	for (i = 0; i < 3; ++i)
		for (j = 0; j < 4; j++)
			a[i][j] = i * 4 + j;
	for (i = 0; i < 3; ++i) {
		for (j = 0; j < 4; j++) {
			cout << a(i, j) << ",";
		}
		cout << endl;
	}
	cout << "next" << endl;
	Array2 b;     b = a;
	for (i = 0; i < 3; ++i) {
		for (j = 0; j < 4; j++) {
			cout << b[i][j] << ",";
		}
		cout << endl;
	}
	return 0;
}