rayzor

view src/stl/vector.h @ 10:235c8b764c0b

optimized swap_buffers
author John Tsiombikas <nuclear@member.fsf.org>
date Thu, 10 Apr 2014 08:03:52 +0300
parents 18bdbcbaee81
children d94a69933a71
line source
1 /* vi:set ft=cpp: */
2 #ifndef VECTOR_H_
3 #define VECTOR_H_
5 template <class T>
6 class vector {
7 private:
8 T *data;
9 size_t num_items, max_items;
11 public:
12 vector()
13 {
14 data = 0;
15 num_items = max_items = 0;
16 }
18 vector(const vector &v)
19 {
20 data = 0;
21 num_items = max_items = 0;
22 resize(v.size());
24 for(size_t i=0; i<v.size(); i++) {
25 data[i] = v.data[i];
26 }
27 }
29 vector &operator =(const vector &v)
30 {
31 if(&v != this) {
32 clear();
33 resize(v.size());
35 for(size_t i=0; i<v.size(); i++) {
36 data[i] = v.data[i];
37 }
38 }
39 return *this;
40 }
42 ~vector()
43 {
44 clear();
45 }
47 void clear()
48 {
49 delete [] data;
50 data = 0;
51 max_items = num_items = 0;
52 }
54 bool empty() const
55 {
56 return num_items == 0;
57 }
59 size_t size() const
60 {
61 return num_items;
62 }
64 void resize(size_t nsz)
65 {
66 if(nsz > 0) {
67 T *newdata = new T[nsz];
68 if(!newdata) return;
70 size_t num = num_items < nsz ? num_items : nsz;
71 for(size_t i=0; i<num; i++) {
72 newdata[i] = data[i];
73 }
75 delete [] data;
76 data = newdata;
77 max_items = nsz;
78 num_items = num;
79 } else {
80 delete [] data;
81 max_items = num_items = 0;
82 }
83 }
85 void push_back(const T &item)
86 {
87 if(num_items >= max_items) {
88 resize(max_items > 0 ? max_items * 2 : 8);
89 }
90 data[num_items++] = item;
91 }
93 void pop_back()
94 {
95 if(--num_items <= 0) {
96 num_items = 0;
97 }
99 if(num_items < max_items / 3) {
100 resize(max_items / 2);
101 }
102 }
104 T &back()
105 {
106 return data[num_items - 1];
107 }
109 const T &back() const
110 {
111 return data[num_items - 1];
112 }
114 T &operator [](int idx)
115 {
116 return data[idx];
117 }
119 const T &operator [](int idx) const
120 {
121 return data[idx];
122 }
123 };
125 #endif // VECTOR_H_