License Public Domain
Lines 91
Keywords
2d (2) array (4) dynamically sized (1) template (3)
Permissions
Viewable by Everyone
Editable by All Siafoo Users

array2D.h Atom Feed 0

In Brief This class creates a 2D array that can set its size at runtime. It is templated to accept any datatype to store.
# 's
  1#ifndef ARRAY2D_H
2#define ARRAY2D_H
3
4#include <iostream>
5
6template<class T>
7class Array2D {
8
9 int m_x;
10 int m_y;
11 T* m_array;
12
13 public:
14 Array2D()
15 {
16 m_array = NULL;
17 m_x = 0;
18 m_y = 0;
19 }
20
21 Array2D(const int x, const int y) {
22 m_array = NULL;
23 initialize(x, y); }
24
25 ~Array2D() {
26 if (m_array)
27 {
28 delete [] m_array;
29 }
30 }
31
32 void initialize(const int x, const int y)
33 {
34 if (m_array)
35 {
36 delete [] m_array;
37 }
38 m_array = new T[x*y];
39 m_x = x;
40 m_y = y;
41 }
42
43 T getXY(const int x, const int y)
44 {
45 if (x >= m_x || y >= m_y)
46 {
47 std::cout << "get request out of array range..." << std::endl;
48 std::cout << "x Max = " << m_x << std::endl;
49 std::cout << "x = " << x << std::endl;
50 std::cout << "y Max = " << m_y << std::endl;
51 std::cout << "y = " << y << std::endl;
52 exit(1);
53 }
54
55 int index = (x * m_y) + y;
56 return m_array[index];
57 }
58
59 T* getPtrXY(const int x, const int y)
60 {
61 if (x >= m_x || y >= m_y)
62 {
63 std::cout << "get request out of array range..." << std::endl;
64 std::cout << "x Max = " << m_x << std::endl;
65 std::cout << "x = " << x << std::endl;
66 std::cout << "y Max = " << m_y << std::endl;
67 std::cout << "y = " << y << std::endl;
68 exit(1);
69 }
70
71 int index = (x * m_y) + y;
72 return &(m_array[index]);
73 }
74
75 void setXY(const int x, const int y, const T data)
76 {
77 if (x >= m_x || y >= m_y)
78 {
79 std::cout << "set request out of array range..." << std::endl
80 << "x = " << x << " y = " << y << std::endl;
81 exit(1);
82 }
83
84 int index = (x * m_y) + y;
85 m_array[index] = data;
86 }
87
88 void getDimensions(int& x, int& y)
89 {
90 x = m_x;
91 y = m_y;
92 }
93
94 T* getArray()
95 {
96 return m_array;
97 }
98
99};
100
101
102#endif

This class creates a 2D array that can set its size at runtime. It is templated to accept any datatype to store.