aboutsummaryrefslogtreecommitdiffstats
path: root/pvector.hpp
blob: 8fb2f1b29a3f4bbeb5acbf658d44129d6cd72e30 (plain)
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
#ifndef PVECTOR_HPP_
#define PVECTOR_HPP_

constexpr unsigned int pvectorSizeChange = 32;

template<class T>
class pvector {
private:
	T* items;
	unsigned int _size;
	unsigned int capacity;

public:
	class iterator {
	private:
		T* pos;
	public:
		iterator(T* p)
			: pos(p) {}

		T operator*(void) const {
			return *pos;
		}

		template<typename N>
		iterator operator+(N inc) const {
			return pos + inc;	
		}

		iterator& operator++(void) {
			++pos;
			return *this;
		}

		template<typename N>
		iterator operator-(N inc) const {
			return pos - inc;
		}

		bool operator>(const iterator& i) const {
			return pos > i.pos;
		}

		bool operator<(const iterator& i) const {
			return pos < i.pos;
		}

		bool operator!=(const iterator& i) const {
			return pos != i.pos;
		}
	};

	pvector(void)
		: items(new T[pvectorSizeChange]), _size(0),
		capacity(pvectorSizeChange) {}

	~pvector(void) {
		delete items;
	}

	inline iterator begin(void) {
		return iterator(items);
	}

	inline iterator end(void) {
		return iterator(items + _size);
	}

	inline unsigned int size(void) const {
		return _size;
	}

	T& push_back(T& t) {
		if (_size >= capacity) {
			auto nItems = new T[capacity + pvectorSizeChange];
			for (unsigned int i = 0; i < capacity; i++)
				nItems[i] = items[i];
			delete items;
			items = nItems;
		}

		auto& r = items[_size++] = t;
		return r;
	}

	template<typename... Args>
	T& emplace_back(Args... args) {
		if (_size >= capacity) {
			auto nItems = new T[capacity + pvectorSizeChange];
			for (unsigned int i = 0; i < capacity; i++)
				nItems[i] = items[i];
			delete items;
			items = nItems;
		}
		auto& r = items[_size++] = T(args...);
		return r;
	}

	void erase(iterator it) {
		for (unsigned int i = it - begin(); i < capacity; i++)
			items[i] = items[i + 1];
		_size--;
	}

	void clear(void) {
		delete items;
		items = new T[pvectorSizeChange];
		_size = 0;
		capacity = pvectorSizeChange;
	}
};

#endif // PVECTOR_HPP_