rayzor

view src/stl/vector.h @ 14:a9a948809c6f

starting the renderer screen, plus misc stuff
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 13 Apr 2014 08:06:21 +0300
parents 70e332156d02
children 5380ff64e83f
line source
1 /* vi:set ft=cpp: */
2 #ifndef VECTOR_H_
3 #define VECTOR_H_
5 #include <stdlib.h>
7 template <class T>
8 class vector {
9 private:
10 T *data;
11 size_t num_items, max_items;
13 public:
14 vector()
15 {
16 data = 0;
17 num_items = max_items = 0;
18 }
20 vector(const vector &v)
21 {
22 data = 0;
23 num_items = max_items = 0;
24 resize(v.size());
26 for(size_t i=0; i<v.size(); i++) {
27 data[i] = v.data[i];
28 }
29 }
31 vector &operator =(const vector &v)
32 {
33 if(&v != this) {
34 clear();
35 resize(v.size());
37 for(size_t i=0; i<v.size(); i++) {
38 data[i] = v.data[i];
39 }
40 }
41 return *this;
42 }
44 ~vector()
45 {
46 clear();
47 }
49 void clear()
50 {
51 delete [] data;
52 data = 0;
53 max_items = num_items = 0;
54 }
56 bool empty() const
57 {
58 return num_items == 0;
59 }
61 size_t size() const
62 {
63 return num_items;
64 }
66 void resize(size_t nsz)
67 {
68 if(nsz > 0) {
69 T *newdata = new T[nsz];
70 if(!newdata) return;
72 size_t num = num_items < nsz ? num_items : nsz;
73 for(size_t i=0; i<num; i++) {
74 newdata[i] = data[i];
75 }
77 delete [] data;
78 data = newdata;
79 max_items = nsz;
80 num_items = num;
81 } else {
82 delete [] data;
83 max_items = num_items = 0;
84 }
85 }
87 void push_back(const T &item)
88 {
89 if(num_items >= max_items) {
90 resize(max_items > 0 ? max_items * 2 : 8);
91 }
92 data[num_items++] = item;
93 }
95 void pop_back()
96 {
97 if(--num_items <= 0) {
98 num_items = 0;
99 }
101 if(num_items < max_items / 3) {
102 resize(max_items / 2);
103 }
104 }
106 T &back()
107 {
108 return data[num_items - 1];
109 }
111 const T &back() const
112 {
113 return data[num_items - 1];
114 }
116 T &operator [](int idx)
117 {
118 return data[idx];
119 }
121 const T &operator [](int idx) const
122 {
123 return data[idx];
124 }
125 };
127 #endif // VECTOR_H_