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.
22 /// maximum length of array.
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_}
48 int size() const { return size_; }
51 void clear() { size_ = 0; }
53 Array() { thearray = 0; max =0; size_ =0; }
55 /// set the size_ to #s#
56 void set_size(int s) {
57 if (s >= max) remax(s);
60 /** POST: size() == s.
61 Warning: contents are unspecified */
63 ~Array() { delete[] thearray; }
65 /// return a "new"ed copy of array
66 T* copy_array() const {
67 T* Tarray = new T[size_];
68 arrcpy(Tarray, thearray, size_);
72 operator T* () const {
75 void operator=(Array const & src) {
77 arrcpy(thearray,src.thearray, size_);
79 Array(const Array & src) {
80 thearray = src.copy_array();
81 max = size_ = src.size_;
84 /// tighten array size_.
85 void precompute () { remax(size_); }
87 /// this makes Array behave like an array
88 T &operator[] (const int i) const {
89 assert(i >=0&&i<size_);
90 return ((T*)thearray)[i];
93 /// add to the end of array
98 // T::operator=(T &) is called here. Safe to use with automatic
100 thearray[size_++] = x;
104 void pop() { size_ -- ; }
106 /// return last entry
108 return (*this)[size_-j-1];
110 T last(int j=0) const {
111 return (*this)[size_-j-1];
113 void swap (int i,int j) {
115 (*this)[i]=(*this)[j];
118 bool empty() { return !size_; }
119 void insert(T k, int j) {
120 assert(j >=0 && j<= size_);
122 for (int i=size_-1; i > j; i--)
123 thearray[i] = thearray[i-1];
127 assert(i >=0&& i < size_);
128 arrcpy(thearray+i, thearray+i+1, size_-i-1);
132 void sort (int (*compare)(T& , T& ),
133 int lower = -1, int upper = -1 ) {
140 swap(lower, (lower+upper)/2);
142 for (int i= lower +1; i <= upper; i++)
143 if (compare(thearray[i], thearray[lower]) < 0 )
146 sort(compare, lower, last-1);
147 sort(compare, last+1, upper);
149 void concat(Array<T> const &src) {
151 set_size(size_ + src.size_);
152 arrcpy(thearray+s,src.thearray, src.size_);
154 Array<T> subvec(int lower, int upper) {
155 assert(lower >= 0 && lower <=upper&& upper <= size_);
159 arrcpy(r.thearray, thearray + lower, s);
165 This template implements a scaleable vector. With (or without) range
166 checking. It may be flaky for objects with complicated con- and
167 destructors. The type T should have a default constructor. It is
168 best suited for simple types, such as int, double or String