/
array.h
98 lines (90 loc) · 2.18 KB
/
array.h
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
// array.h - copyright (C) 2001-2011 by Patrick Hanevold
#ifndef _ARRAY_H_
#define _ARRAY_H_
#include <assert.h>
#include <stdlib.h>
//class OStream;
#define __bs 32
//namespace base{
template <typename T> class Array{
public: Array(){
count=0;
list=0;
}
Array(int n){
count=0;
list=0;
init(n);
}
Array(const Array<T> &a){
count = a.count;
list = (T**)malloc(count*sizeof(T*));
for(int n=0; n<count; n++){ list[n]=new T(); *(list[n])=*(a.list[n]); }
}
~Array(){
if(list){
for(int n=0; n<count; n++){ delete list[n]; }
}
free(list);
}
void init(int n){
if(list){
for(int n=0; n<count; n++){ delete list[n]; }
}
count=n;
list = (T**)realloc(list,sizeof(T*)*count);
for(int n=0; n<count; n++) list[n]=new T();
}
Array<T> &operator=(const Array<T> &a){
if(list){
for(int n=0; n<count; n++){ delete list[n]; }
}
free(list);
count = a.count;
list = (T**)malloc(count*sizeof(T*));
for(int n=0; n<count; n++){ list[n]=new T(); *(list[n])=*(a.list[n]); }
return *this;
}
void clear(){
if(list){
for(int n=0; n<count; n++){ delete list[n]; }
}
free(list);
list=0;
count=0;
}
void remove(int r){
count--;
for(int n=r; n<count; n++) list[n]=list[n+1];
list = (T**)realloc(list,sizeof(T*)*count);
}
void insert(int at, T t){
count++;
list = (T**)realloc(list,sizeof(T*)*count);
for(int n=count-1; n>=at+1; n--) list[n]=list[n-1];
list[at]=new T();
*list[at]=t;
}
void add(T t){
count++;
list = (T**)realloc(list,sizeof(T*)*count);
list[count-1]=new T();
*list[count-1]=t;
}
int getCount() const{ return count; }
T &operator[](int i) const{
assert(i>=0&&i<count);
return *list[i];
}
//friend OStream &operator<<(OStream &out, const Array<T> &in){ return in.out(out); }
//OStream &out(OStream &out) const{
// out << count;
// for(int n=0; n<count; n++) out << *list[n];
// return out;
//}
private:
int count;
T **list;
};
//}
#endif