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++)
18 ///scaleable array template, for T with def ctor.
28 /// stretch or shrink array.
29 void remax(int newmax) {
30 T* newarr = new T[newmax];
31 size = (newmax < size) ? newmax : size;
32 arrcpy(newarr, thearray, size);
43 assert(max >= size && size >=0);
44 if (max) assert(thearray);
46 /// report the size. See {setsize}
47 int sz() const { return size; }
50 void clear() { size = 0; }
52 svec() { thearray = 0; max =0; size =0; }
53 /// set the size to #s#
54 void set_size(int s) {
55 if (s >= max) remax(s);
59 Warning: contents are unspecified */
61 ~svec() { delete[] thearray; }
63 /// return a "new"ed copy of array
64 T* copy_array() const {
65 T* Tarray = new T[size];
66 arrcpy(Tarray, thearray, size);
70 operator T* () const {
73 void operator=(svec const & src) {
75 arrcpy(thearray,src.thearray, size);
77 svec(const svec & src) {
78 thearray = src.copy_array();
79 max = size = src.size;
82 /// tighten array size.
83 void precompute () { remax(size); }
85 /// this makes svec behave like an array
86 T &operator[] (const int i) const {
87 assert(i >=0&&i<size);
88 return ((T*)thearray)[i];
91 /// add to the end of array
96 // T::operator=(T &) is called here. Safe to use with automatic
102 void pop() { size -- ; }
104 /// return last entry
106 return (*this)[size-j-1];
108 void swap (int i,int j) {
110 (*this)[i]=(*this)[j];
113 bool empty() { return !size; }
114 void insert(T&k, int j) {
115 assert(j >=0 && j<= size);
117 for (int i=size-1; i > j; i--)
118 thearray[i] = thearray[i-1];
122 assert(i >=0&& i < size);
123 arrcpy(thearray+i, thearray+i+1, size-i-1);
127 void sort (int (*compare)(T& , T& ),
128 int lower = -1, int upper = -1 ) {
135 swap(lower, (lower+upper)/2);
137 for (int i= lower +1; i <= upper; i++)
138 if (compare(thearray[i], thearray[lower]) < 0 )
141 sort(compare, lower, last-1);
142 sort(compare, last+1, lower);
144 void concat(svec<T> const &src) {
146 set_size(size + src.size);
147 arrcpy(thearray+s,src.thearray, src.size);
152 This template implements a scaleable vector. With (or without) range
153 checking. It may be flaky for objects with complicated con- and
154 destructors. The type T should have a default constructor. It is
155 best suited for simple types, such as int, double or String
159 /// A simple stack based on svec.
161 class sstack : svec<T> {
163 T top() { return last(); }
170 void push(T l) { add(l); }
171 bool empty() { return svec<T>::empty(); }
174 Same as for #svec# goes here.