1 #ifndef __VECTOR_H__
2 #define __VECTOR_H__
3 
4 #include "iterator.h"
5 #include "base.h"
6 
Max(const T & x,const T & y)7 template<class T> inline T Max (const T &x, const T &y) { return x > y ? x : y; }
Min(const T & x,const T & y)8 template<class T> inline T Min (const T &x, const T &y) { return x < y ? x : y; }
9 
10 
11 template<class T> class TVector {
12 protected:
13 	int capacity;
14 	T * d;
15 public:
TVector()16 	TVector () { d = 0; capacity = 0; }
17 	TVector(const TVector&x);
18 	TVector(int sz);
~TVector()19 	~TVector () { delete[] d; }
20 
21 	const T &operator[] (int x) const { ASSERT (x >= 0 && x < capacity && d); return d[x]; }
22     T& operator[](int i) { ASSERT(i>=0 && i<capacity && d); return d[i];  }
23 	TVector & operator = (const TVector &x);
24 
25 	void	Realloc(int nsz);
26 	void	DeleteAll();
27 
28 	typedef viterator<T> iterator;
29 	typedef const_viterator<T> const_iterator;
30 
begin()31 	virtual iterator begin () const		{ if (d) return &*d; else return 0; }
end()32 	virtual iterator end () const		{ if (d) return d+capacity; else return 0; }
33 
size()34 	int size() const			{ return capacity; }
35 	virtual iterator push_back (T x);
36 };
37 
38 #define VECTOR(x,y) typedef TVector<x> y;
39 #define VECTORC(x,y) VECTOR(x,y)
40 
Realloc(int nsz)41 template<class T> void TVector<T>::Realloc (int nsz) {
42 	T *newd = new T [nsz];
43 	for (int i = 0; i < Min (this->capacity, nsz); i ++)
44 		newd[i] = d[i];
45 	delete[] d;
46 	d = newd;
47 	capacity = nsz;
48 }
49 
DeleteAll()50 template<class T> void TVector<T>::DeleteAll () {
51 	delete[] d;
52 	capacity = 0;
53 	d = 0;
54 }
55 
push_back(T x)56 template<class T> typename TVector<T>::iterator TVector<T>::push_back (T x)
57 {
58 	Realloc (capacity + 1);
59 	d[capacity-1] = x;
60 	return d+capacity-1;
61 }
62 
63 
TVector(const TVector & x)64 template<class T> TVector<T>::TVector(const TVector&x)
65 {
66 	capacity = x.capacity;
67 	d= new T [capacity];
68 	for(int i=0; i<capacity; i++) d[i] = x[i];
69 }
70 
71 template<class T> TVector<T> & TVector<T>::operator = (const TVector &x)
72 {
73 	delete[] d;
74 	capacity = x.capacity;
75 	d= new T [capacity];
76 	for(int i=0; i<capacity; i++) d[i] = x[i];
77 	return *this;
78 }
79 
TVector(int sz)80 template<class T> TVector<T>::TVector(int sz)
81 {
82 	capacity = sz;
83 	d= new T [sz];
84 }
85 
86 #endif
87