-
Notifications
You must be signed in to change notification settings - Fork 0
/
A2D.h
150 lines (137 loc) · 2.37 KB
/
A2D.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
// $Id: A2D.h,v 1.6 2009/06/24 18:03:55 samn Exp $
#pragma once
template < typename T >
T **Allocate2DArray( int nRows, int nCols)
{
if(nRows<=0 || nCols<=0) return 0x0;
T **ppi;
T *pool;
T *curPtr;
//(step 1) allocate memory for array of elements of column
ppi = new T*[nRows];
//(step 2) allocate memory for array of elements of each row
pool = new T [nRows * nCols];
// Now point the pointers in the right place
curPtr = pool;
for( int i = 0; i < nRows; i++)
{
*(ppi + i) = curPtr;
curPtr += nCols;
}
return ppi;
}
template < typename T >
void Free2DArray(T** Array)
{
delete [] *Array;
delete [] Array;
}
template < class T >
class AutoFree2D
{
T** m_p;
public:
AutoFree2D(T** p)
:m_p(p)
{
}
~AutoFree2D()
{
Free2DArray(m_p);
}
};
template < class T >
class A2D
{
T** m_p;
int m_iRows;
int m_iCols;
//A2D(const A2D&);
public:
//get # rows
int Rows() const { return m_iRows; }
//get # cols
int Cols() const { return m_iCols; }
//construct empty
A2D(T** p,int iRows,int iCols)
:m_p(p),
m_iRows(iRows),
m_iCols(iCols)
{
}
A2D()
:m_p(0),
m_iRows(0),
m_iCols(0)
{
}
A2D(const A2D& r)
{ m_p=0;
Init(r.Rows(),r.Cols());
int i,j;
for(i=0;i<m_iRows;i++)
for(j=0;j<m_iCols;j++)
m_p[i][j]=r[i][j];
}
A2D& operator=(const A2D& r)
{ if(&r==this) return *this;
Init(r.Rows(),r.Cols());
int i,j;
for(i=0;i<m_iRows;i++)
for(j=0;j<m_iCols;j++)
m_p[i][j]=r[i][j];
return *this;
}
//init with specified size
bool Init(int iRows,int iCols)
{
Clear();
m_p = Allocate2DArray<T>(iRows,iCols);
if(!m_p)
return false;
m_iRows = iRows;
m_iCols = iCols;
return true;
}
//construct with specified size
A2D(int iRows,int iCols)
:m_p(0)
{
Init(iRows,iCols);
}
//destructor
virtual ~A2D()
{
Clear();
}
//free memory
void Clear()
{
if(m_p)
Free2DArray<T>(m_p);
m_p=0;
m_iRows=m_iCols=0;
}
//get 2D pointer
T** GetP()
{
return m_p;
}
//get row pointer
T* operator[](int i)
{
return m_p[i];
}
T* operator[](int i) const
{
return m_p[i];
}
//fill with val
void Fill(const T& val)
{
int x,y;
for(y=0;y<m_iRows;y++)
for(x=0;x<m_iCols;x++)
m_p[y][x]=val;
}
};