Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016 #include <stdlib.h>
00017 #include <shogun/lib/memory.h>
00018 #include <shogun/mathematics/Math.h>
00019
00020 #ifndef VARRAY_H__
00021 #define VARRAY_H__
00022
00023 namespace shogun
00024 {
00039 template<class T> class v_array
00040 {
00041 public:
00042
00047 v_array()
00048 {
00049 begin = NULL;
00050 end = NULL;
00051 end_array = NULL;
00052 }
00053
00062 T& operator[](unsigned int i) { return begin[i]; }
00063
00069 inline T last() { return *(end-1); }
00070
00076 inline T pop() { return *(--end); }
00077
00083 inline bool empty() { return begin == end; }
00084
00089 inline void decr() { end--; }
00090
00096 inline unsigned int index() { return end-begin; }
00097
00102 inline void erase() { end = begin; }
00103
00109 void push(const T &new_elem);
00110
00117 void push_many(const T* new_elem, size_t num);
00118
00125 void reserve(size_t length);
00126
00133 void calloc_reserve(size_t length);
00134
00141 v_array<T> pop(v_array< v_array<T> > &stack);
00142
00143 public:
00144
00146 T* begin;
00147
00149 T* end;
00150
00152 T* end_array;
00153
00154 };
00155
00156 template<class T>
00157 inline void v_array<T>::push(const T &new_elem)
00158 {
00159 if(end == end_array)
00160 {
00161 size_t old_length = end_array - begin;
00162 size_t new_length = 2 * old_length + 3;
00163
00164 begin = SG_REALLOC(T, begin, new_length);
00165 end = begin + old_length;
00166 end_array = begin + new_length;
00167 }
00168 *(end++) = new_elem;
00169 }
00170
00171 template<class T>
00172 inline void v_array<T>::push_many(const T* new_elem, size_t num)
00173 {
00174 if(end+num >= end_array)
00175 {
00176 size_t length = end - begin;
00177 size_t new_length = CMath::max(2 * (size_t)(end_array - begin) + 3,
00178 end - begin + num);
00179 begin = SG_REALLOC(T, begin, new_length);
00180 end = begin + length;
00181 end_array = begin + new_length;
00182 }
00183 memcpy(end, new_elem, num * sizeof(T));
00184 end += num;
00185 }
00186
00187 template<class T>
00188 inline void v_array<T>::reserve(size_t length)
00189 {
00190 size_t old_length = end_array-begin;
00191 begin = SG_REALLOC(T, begin, length);
00192 if (old_length < length)
00193 bzero(begin + old_length, (length - old_length)*sizeof(T));
00194
00195 end = begin;
00196 end_array = begin + length;
00197 }
00198
00199 template<class T>
00200 inline void v_array<T>::calloc_reserve(size_t length)
00201 {
00202 begin = SG_CALLOC(T, length);
00203 end = begin;
00204 end_array = begin + length;
00205 }
00206
00207 template<class T>
00208 inline v_array<T> v_array<T>::pop(v_array< v_array<T> > &stack)
00209 {
00210 if (stack.end != stack.begin)
00211 return *(--stack.end);
00212 else
00213 return v_array<T>();
00214 }
00215 }
00216 #endif // VARRAY_H__