License Public Domain
Lines 104
Keywords
3d (3) array (4) template (3)
Permissions
Viewable by Everyone
Editable by All Siafoo Users
Hide
Siafoo is here to make coding less frustrating and to save you time. Join Siafoo Now or Learn More

array3D.h Atom Feed 0

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

This class will dynamically allocate a 3D array at runtime. It is templated to accept any datatype.