2 (c) Han-Wen Nienhuys 1995,96
4 Distributed under GNU GPL
11 /// copy a bare (C-)array from #src# to #dest# sized #count#
13 inline void arrcpy(T*dest, T*src, int count) {
14 for (int i=0; i < count ; i++)
20 Scaleable array/stack template, for a type T with default constructor.
23 This template implements a scaleable vector. With (or without) range
24 checking. It may be flaky for objects with complicated con- and
25 destructors. The type T should have a default constructor. It is
26 best suited for simple types, such as int, double or String, it
27 provides a paranoidly safe replacement for the new T[int] construct.
29 It uses stack terminology, (push, pop, top), and can be used as a stack.
36 /// maximum length of array.
42 /// stretch or shrink array.
43 void remax(int newmax) {
44 T* newarr = new T[newmax];
45 size_ = (newmax < size_) ? newmax : size_;
46 arrcpy(newarr, thearray, size_);
57 assert(max >= size_ && size_ >=0);
58 if (max) assert(thearray);
63 int size() const { return size_; }
66 void clear() { size_ = 0; }
68 Array() { thearray = 0; max =0; size_ =0; }
71 /** set the size_ to #s#.
73 Warning: contents are unspecified */
74 void set_size(int s) {
75 if (s >= max) remax(s);
79 ~Array() { delete[] thearray; }
81 /// return a "new"ed copy of array
82 T* copy_array() const {
83 T* Tarray = new T[size_];
84 arrcpy(Tarray, thearray, size_);
88 operator T* () const {
91 void operator=(Array const & src) {
93 arrcpy(thearray,src.thearray, size_);
95 Array(Array const & src) {
96 thearray = src.copy_array();
97 max = size_ = src.size_;
100 /// tighten array size_.
101 void precompute () { remax(size_); }
103 /// this makes Array behave like an array
104 T &operator[] (const int i) const {
105 assert(i >=0&&i<size_);
106 return ((T*)thearray)[i];
109 /// add to the end of array
114 // T::operator=(T &) is called here. Safe to use with automatic
116 thearray[size_++] = x;
118 /// remove and return last entry
125 /// access last entry
127 return (*this)[size_-j-1];
129 /// return last entry
130 T top (int j=0) const {
131 return (*this)[size_-j-1];
135 void swap (int i,int j) {
137 (*this)[i]=(*this)[j];
140 bool empty() { return !size_; }
141 void insert(T k, int j) {
142 assert(j >=0 && j<= size_);
144 for (int i=size_-1; i > j; i--)
145 thearray[i] = thearray[i-1];
149 assert(i >=0&& i < size_);
150 arrcpy(thearray+i, thearray+i+1, size_-i-1);
154 void sort (int (*compare)( T const&,T const&),
155 int lower = -1, int upper = -1 ) {
162 swap(lower, (lower+upper)/2);
164 for (int i= lower +1; i <= upper; i++)
165 if (compare(thearray[i], thearray[lower]) < 0 )
168 sort(compare, lower, last-1);
169 sort(compare, last+1, upper);
171 void concat(Array<T> const &src) {
173 set_size(size_ + src.size_);
174 arrcpy(thearray+s,src.thearray, src.size_);
176 Array<T> subvec(int lower, int upper) {
177 assert(lower >= 0 && lower <=upper&& upper <= size_);
181 arrcpy(r.thearray, thearray + lower, s);