edits
[iotcloud.git] / version2 / src / C / vector.h
1 #ifndef CPPVECTOR_H
2 #define CPPVECTOR_H
3 #include <string.h>
4 #define VECTOR_DEFCAP 8
5
6 template<typename type>
7 class Vector {
8 public:
9         Vector(uint _capacity = VECTOR_DEFCAP) :
10                 size(0),
11                 capacity(_capacity),
12                 array((type *) ourmalloc(sizeof(type) * _capacity)) {
13         }
14
15         Vector(uint _capacity, type *_array)  :
16                 size(_capacity),
17                 capacity(_capacity),
18                 array((type *) ourmalloc(sizeof(type) * _capacity)) {
19                 memcpy(array, _array, capacity * sizeof(type));
20         }
21
22         void pop() {
23                 size--;
24         }
25
26         type last() const {
27                 return array[size - 1];
28         }
29
30         void setSize(uint _size) {
31                 if (_size <= size) {
32                         size = _size;
33                         return;
34                 } else if (_size > capacity) {
35                         array = (type *)ourrealloc(array, _size * sizeof(type));
36                         capacity = _size;
37                 }
38                 bzero(&array[size], (_size - size) * sizeof(type));
39                 size = _size;
40         }
41
42         void push(type item) {
43                 if (size >= capacity) {
44                         uint newcap = capacity << 1;
45                         array = (type *)ourrealloc(array, newcap * sizeof(type));
46                         capacity = newcap;
47                 }
48                 array[size++] = item;
49         }
50
51         type get(uint index) const {
52                 return array[index];
53         }
54
55         void setExpand(uint index, type item) {
56                 if (index >= size)
57                         setSize(index + 1);
58                 set(index, item);
59         }
60
61         void set(uint index, type item) {
62                 array[index] = item;
63         }
64
65         uint getSize() const {
66                 return size;
67         }
68
69         bool isEmpty() const {
70                 return size == 0;
71         }
72
73         ~Vector() {
74                 ourfree(array);
75         }
76
77         void clear() {
78                 size = 0;
79         }
80
81         type *expose() {
82                 return array;
83         }
84         CMEMALLOC;
85 private:
86         uint size;
87         uint capacity;
88         type *array;
89 };
90 #endif