1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
|
/*
* A generic template list class.
* Fairly typical of the list example you would
* find in any c++ book.
*/
#ifndef GENERIC_LIST_H
#define GENERIC_LIST_H
#include <assert.h>
#include <stdio.h>
template<class Type> class List {
public:
List(int s=0);
~List();
void allocate(int s);
void SetSize(int s);
void Pack();
void Add(Type);
void AddUnique(Type);
int Contains(Type);
void Remove(Type);
void DelIndex(int i);
Type * element;
int num;
int array_size;
Type &operator[](int i){
assert(i>=0 && i<num);
return element[i];}
};
template<class Type>
List<Type>::List(int s){
num=0;
array_size = 0;
element = NULL;
if(s) {
allocate(s);
}
}
template<class Type>
List<Type>::~List(){
delete element;
}
template<class Type>
void List<Type>::allocate(int s){
assert(s>0);
assert(s>=num);
Type *old = element;
array_size =s;
element = new Type[array_size];
assert(element);
for(int i=0;i<num;i++){
element[i]=old[i];
}
if(old) delete old;
}
template<class Type>
void List<Type>::SetSize(int s){
if(s==0) { if(element) delete element;}
else { allocate(s); }
num=s;
}
template<class Type>
void List<Type>::Pack(){
allocate(num);
}
template<class Type>
void List<Type>::Add(Type t){
assert(num<=array_size);
if(num==array_size) {
allocate((array_size)?array_size *2:16);
}
//int i;
//for(i=0;i<num;i++) {
// dissallow duplicates
// assert(element[i] != t);
//}
element[num++] = t;
}
template<class Type>
int List<Type>::Contains(Type t){
int i;
int count=0;
for(i=0;i<num;i++) {
if(element[i] == t) count++;
}
return count;
}
template<class Type>
void List<Type>::AddUnique(Type t){
if(!Contains(t)) Add(t);
}
template<class Type>
void List<Type>::DelIndex(int i){
assert(i<num);
num--;
while(i<num){
element[i] = element[i+1];
i++;
}
}
template<class Type>
void List<Type>::Remove(Type t){
int i;
for(i=0;i<num;i++) {
if(element[i] == t) {
break;
}
}
DelIndex(i);
for(i=0;i<num;i++) {
assert(element[i] != t);
}
}
#endif
|