資料存取物件化之二
kowala's home
http://kowala21.blogspot.com
繼前一篇 物件化的資料存取-動態二維陣列物件,再接再厲推出了三維陣列物件,其實原理都一樣,就是ㄧ串指標陣列,後面接個 int 元素陣列(本例為int),示意如下。
二維陣列物件 指標陣列->int 元素陣列
三維陣列物件 指標陣列-> 指標陣列->int 元素陣列
然後把它封裝起來,三維陣列物件應該很夠用了,已能處理大多數的問題了。
先來看看執行結果
紅色圈選處是測試寫入,最下面三個是讀出測試,完整程式碼如下。
#include <cstdlib>
#include <iostream>
using namespace std;
/*******************************************************************
3D array Object
2011-10-12
kowala's home http://kowala21.blogspot.com
ref: http://www.programmer-club.com.tw/ShowSameTitleN/c/37868.html
********************************************************************/
typedef int** array3d;
class SrcData3D{
array3d *matrix;
int m_rows;
int m_cols;
int m_hight;
public:
SrcData3D();
void initData(int row,int col,int hight,int var);
void relaxData();
void dumpData();
void setData(int row,int col,int hight,int var);
int getData(int row,int col,int hight);
};
int main(int argc, char *argv[]){
system("cls");
int row=3,col=7,hight=5;
SrcData3D s3d;
cout << "initial 3D array by -1 ..." << endl;
s3d.initData(row,col,hight,-1);
s3d.dumpData();
cout << "set value to 3D array..." << endl;
s3d.setData(0,1,0,1);
s3d.setData(0,2,1,2);
s3d.setData(0,3,2,3);
s3d.setData(1,2,1,4);
s3d.setData(1,3,2,5);
s3d.setData(1,4,3,6);
s3d.setData(2,3,2,7);
s3d.setData(2,4,3,8);
s3d.setData(2,5,4,9);
s3d.dumpData();
cout << "get value from 3D array..." << endl;
cout << "[0,3,2]=" << s3d.getData(0,3,2) << endl;
cout << "[1,4,3]=" << s3d.getData(1,4,3) << endl;
cout << "[2,5,4]=" << s3d.getData(2,5,4) << endl;
s3d.relaxData();
system("PAUSE");
return EXIT_SUCCESS;
}
//建構子
SrcData3D::SrcData3D(){ m_rows=1;m_cols=2;m_hight=3;}
//設定參數
void SrcData3D::setData(int row,int col,int hight,int var){ matrix[row][col][hight]=var;}
//取出參數
int SrcData3D::getData(int row,int col,int hight){ return matrix[row][col][hight];}
//初始化陣列
void SrcData3D::initData(int row,int col,int hight,int var){
m_rows=row;m_cols=col;m_hight=hight;
SrcData3D::matrix=new array3d[m_rows];
for(int i=0;i<m_rows;i++){
SrcData3D::matrix[i]=new int*[m_cols];
for(int j=0;j<m_cols;j++){
SrcData3D::matrix[i][j]=new int[m_hight];
for(int k=0;k<m_hight;k++){
SrcData3D::matrix[i][j][k]=var;
}
}
}
}
//釋放陣列
void SrcData3D::relaxData(){
for(int i=0;i<m_rows;i++){
for(int j=0;j<m_cols;j++){
delete [] SrcData3D::matrix[i][j];
}
delete [] SrcData3D::matrix[i];
}
delete [] SrcData3D::matrix;
}
//傾印資料
void SrcData3D::dumpData(){
cout << "rows=" << m_rows << ",cols=" << m_cols << ",hight=" << m_hight << endl;
for(int i=0;i<m_rows;i++){
for(int j=0;j<m_cols;j++){
for(int k=0;k<m_hight;k++){
cout << "[" << i << "," << j << "," << k << "]=" << SrcData3D::matrix[i][j][k] << " ";
}
cout << endl;
}
cout << endl;
}
cout << endl;
}
沒有留言:
張貼留言
請提供您的寶貴意見 ;-)