File: dynamic_array.h

package info (click to toggle)
brian 2.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,872 kB
  • sloc: python: 51,820; cpp: 2,033; makefile: 108; sh: 72
file content (87 lines) | stat: -rw-r--r-- 1,431 bytes parent folder | download | duplicates (4)
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
#ifndef _BRIAN_DYNAMIC_ARRAY_H
#define _BRIAN_DYNAMIC_ARRAY_H

#include<vector>

/*
 * 2D Dynamic array class
 *
 * Efficiency note: if you are regularly resizing, make sure it is the first dimension that
 * is resized, not the second one.
 *
 */
template<class T>
class DynamicArray2D
{
	int old_n, old_m;
	std::vector< std::vector<T>* > data;
public:
	int n, m;
	DynamicArray2D(int _n=0, int _m=0)
	{
		old_n = 0;
		old_m = 0;
		resize(_n, _m);
	};
	~DynamicArray2D()
	{
		resize(0, 0); // handles deallocation
	}
	void resize()
	{
		if(old_n!=n)
		{
			if(n<old_n)
			{
				for(int i=n; i<old_n; i++)
				{
					if(data[i]) delete data[i];
					data[i] = 0;
				}
			}
			data.resize(n);
			if(n>old_n)
			{
				for(int i=old_n; i<n; i++)
				{
					data[i] = new std::vector<T>;
				}
			}
			if(old_m!=m)
			{
				for(int i=0; i<n; i++)
					data[i]->resize(m);
			} else if(n>old_n)
			{
				for(int i=old_n; i<n; i++)
					data[i]->resize(m);
			}
		} else if(old_m!=m)
		{
			for(int i=0; i<n; i++)
			{
				data[i]->resize(m);
			}
		}
		old_n = n;
		old_m = m;
	};
	void resize(int _n, int _m)
	{
		n = _n;
		m = _m;
		resize();
	}
	// We cannot simply use T& as the return type here, since we don't
	// get a bool& out of a std::vector<bool>
	inline typename std::vector<T>::reference operator()(int i, int j)
	{
		return (*data[i])[j];
	}
	inline std::vector<T>& operator()(int i)
	{
		return (*data[i]);
	}
};

#endif