File: array.h

package info (click to toggle)
amoeba 1.1-17
  • links: PTS
  • area: contrib
  • in suites: etch, etch-m68k
  • size: 732 kB
  • ctags: 971
  • sloc: cpp: 8,315; makefile: 178
file content (101 lines) | stat: -rw-r--r-- 1,685 bytes parent folder | download | duplicates (11)
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
/*
 * An automatically scaling array implementation -- no bounds checking.
 */

#ifndef _ARRAY_H
#define _ARRAY_H

#include <stdlib.h>

template <class T> class Array {
	typedef T * iterator;
	typedef const T * const_iterator;
	
protected:
	T *array;
	unsigned int room, elem;
	
public:
	Array()
	{
		this->array = (T *)(malloc(sizeof(T)));
		this->room = 1;
		this->elem = 0;
	}
	
	~Array()
	{
		free(this->array);
		this->array = NULL;
	}

	const Array<T> &operator=(Array<T> const &other)
	{
		if (this != &other) {
			free(this->array);
			this->room = this->elem = other.num_elems();
			this->array = (T *)malloc(this->room * sizeof(T));
			memcpy(this->array, other.get_array(), this->room * sizeof(T));
		}
		return *this;
	}
	
	inline T &operator[](const unsigned int index)
	{
		if (index >= room) {
			while (index >= room) {
				room <<= 1;
			}
			this->array = (T *)realloc(this->array, room * sizeof(T));
		}
		if (index >= elem) elem = index + 1;
		return this->array[index];
	}

	inline T operator[](const unsigned int index) const
	{
		return this->array[index];
	}

	/* duplicated code here, but I'm too lazy to fix it ;-) */
	inline void add_end(T t)
	{
		if (elem == room) {
			room <<= 1;
			this->array = (T *)realloc(this->array, room * sizeof(T));
		}
		this->array[this->elem++] = t;
	}

	inline int num_elems() const
	{
		return elem;
	}

	inline T *get_array() const
	{
		return this->array;
	}

	inline iterator begin()
	{
		return array;
	}

	inline const_iterator begin() const
	{
		return array;
	}
	
	inline iterator end()
	{
		return array + elem;
	}
	
	inline const_iterator end() const
	{
		return array + elem;
	}
};

#endif /* defined(_ARRAY_H) */