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_block(int i, int n) {
50 if( i >= total || !n ) return;
51 for( n+=i; n<total; ++i,++n ) values[i] = values[n];
54 void remove_object_block(int i, int n) {
55 if( i >= total || !n ) return;
56 for( int j=i,k=n; --k>=0 && j<total; ++j ) del_value(j);
57 for( n+=i; n<total; ++i,++n ) values[i] = values[n];
60 void remove(TYPE value) {
62 for( int in=0; in<total; ++in )
63 if( values[in] != value ) values[out++] = values[in];
66 void remove_object(TYPE value) { remove(value); del(value); }
67 void remove_object_number(int i) {
68 if( i < total ) { del_value(i); remove_number(i); }
69 else fprintf(stderr, "ArrayList<TYPE>::remove_object_number:"
70 " number %d out of range %d.\n", i, total);
72 int number_of(TYPE value) {
73 for( int i=0; i<total; ++i )
74 if( values[i] == value ) return i;
77 void remove_all() { total = 0; }
78 void remove_all_objects() {
79 for( int i=0; i<total; ++i ) del(values[i]);
82 TYPE &last() { return values[total - 1]; }
84 void set_array_delete() { dtype = d_array; }
85 void set_free() { dtype = d_free; }
86 int size() { return total; }
88 if( i < total ) return values[i];
89 fprintf(stderr,"ArrayList<TYPE>::get number=%d total=%d\n",i,total);
92 TYPE set(int i, TYPE value) {
93 if( i < total ) return values[i] = value;
94 fprintf(stderr,"ArrayList<TYPE>::set number=%d total=%d\n",i,total);
97 TYPE &operator [](int i) { return values[i]; }
98 void sort(int (*cmp)(TYPE *a, TYPE *b) = 0) {
99 return qsort(values, size(), sizeof(TYPE),
100 (int(*)(const void *, const void *))(cmp ? cmp : cmpr));
103 ArrayList() { total = 0; dtype = d_delete; values = new TYPE[avail = 16]; }
104 ~ArrayList() { delete [] values; }
108 void ArrayList<TYPE>::reallocate(int n)
110 TYPE* newvalues = new TYPE[avail=n];
111 for( int i=total; --i>=0; ) newvalues[i] = values[i];
112 delete [] values; values = newvalues;