8 enum { d_none, d_delete, d_array, d_free, };
10 void reallocate(int n);
11 void del(TYPE &value) {
13 case d_delete: delete value; break;
14 case d_array: delete [] value; break;
15 case d_free: free((void*)value); break;
18 void del_value(int i) { del(values[i]); }
19 static int cmpr(TYPE *a, TYPE *b) {
20 if( *a == *b ) return 0;
21 return *a > *b ? 1 : -1;
27 void allocate(int total) { if( total >= avail ) reallocate(total); }
30 if( total >= avail ) reallocate(total*2);
33 TYPE &append(TYPE value) { return append() = value; }
34 TYPE &insert(TYPE value, int n) {
36 for(int i=total; --i>n; ) values[i]=values[i-1];
37 return values[n] = value;
39 void remove() { --total; }
40 void remove_object() {
41 if( total > 0 ) { del_value(total-1); remove(); }
42 else fprintf(stderr, "ArrayList<TYPE>::remove_object: array is 0 length.\n");
44 void remove_number(int n) {
45 if( n >= total ) return;
46 while( ++n<total ) values[n-1]=values[n];
49 void remove(TYPE value) {
51 for( int in=0; in<total; ++in )
52 if( values[in] != value ) values[out++] = values[in];
55 void remove_object(TYPE value) { remove(value); del(value); }
56 void remove_object_number(int i) {
57 if( i < total ) { del_value(i); remove_number(i); }
58 else fprintf(stderr, "ArrayList<TYPE>::remove_object_number:"
59 " number %d out of range %d.\n", i, total);
61 int number_of(TYPE value) {
62 for( int i=0; i<total; ++i )
63 if( values[i] == value ) return i;
66 void remove_all() { total = 0; }
67 void remove_all_objects() {
68 for( int i=0; i<total; ++i ) del(values[i]);
71 TYPE &last() { return values[total - 1]; }
73 void set_array_delete() { dtype = d_array; }
74 void set_free() { dtype = d_free; }
75 int size() { return total; }
77 if( i < total ) return values[i];
78 fprintf(stderr,"ArrayList<TYPE>::get number=%d total=%d\n",i,total);
81 TYPE set(int i, TYPE value) {
82 if( i < total ) return values[i] = value;
83 fprintf(stderr,"ArrayList<TYPE>::set number=%d total=%d\n",i,total);
86 TYPE &operator [](int i) { return values[i]; }
87 void sort(int (*cmp)(TYPE *a, TYPE *b) = 0) {
88 return qsort(values, size(), sizeof(TYPE),
89 (int(*)(const void *, const void *))(cmp ? cmp : cmpr));
92 ArrayList() { total = 0; dtype = d_delete; values = new TYPE[avail = 16]; }
93 ~ArrayList() { delete [] values; }
97 void ArrayList<TYPE>::reallocate(int n)
99 TYPE* newvalues = new TYPE[avail=n];
100 for( int i=total; --i>=0; ) newvalues[i] = values[i];
101 delete [] values; values = newvalues;