-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.cpp
141 lines (126 loc) · 2.36 KB
/
vector.cpp
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
131
132
133
134
135
136
137
138
139
140
141
#include<iostream>
using namespace std;
template <class Type> class Vector;
template<class T> ostream & operator <<(ostream &,const Vector<T> &);
template <class Type> class VectorItem
{
Type item;
VectorItem *next;
VectorItem(const Type &t):item(t),next(0){}
friend class Vector<Type>;
friend ostream & operator << <Type>(ostream &,const Vector<Type> &);
};
template <class Type> class Vector
{
private:
VectorItem<Type> *head;
VectorItem<Type> *tail;
void destroy();
void copy_elements(const Vector &);
public:
Vector():head(0),tail(0){}
Vector(const Vector &v):head(0),tail(0)
{
copy_elements(v);
}
Vector & operator=(const Vector &);
~Vector()
{
destroy();
}
Type & front()
{
return head->item;
}
const Type & front() const
{
return head->item;
}
void push_back(const Type &);
void pop();
bool empty() const
{
return head==0;
}
template <class It> Vector(It beg,It end): head(0),tail(0)
{
copy_elements(beg,end);
}
template <class Iter>void assign(Iter,Iter);
template <class It>void copy_elements(It,It);
friend ostream & operator << <Type>(ostream &,const Vector<Type> &);
};
template<class Type> void Vector<Type>::push_back(const Type &val)
{
VectorItem<Type>*pt=new VectorItem<Type>(val);
if(head==0)
{
head=tail=pt;
}
else
{
pt->next=head;
head=pt;
}
}
template <class Type>void Vector<Type>::pop()
{
VectorItem<Type>*p;
p=head;
head=head->next;
delete p;
}
template<class Type>void Vector<Type>::destroy()
{
while(!empty())
{
pop();
}
}
template<class Type> void Vector<Type>::copy_elements(const Vector &orig)
{
for(VectorItem <Type> *pt=orig.head;pt;pt=pt->next)
{
push_back(pt->Item);
}
}
template <class Type> Vector<Type> & Vector<Type>::operator=(const Vector &v)
{
(*this).destroy();
(*this).copy_elements(v);
return *this;
}
template <class T> template<class Iter>void Vector<T>::assign(Iter beg,Iter end)
{
destroy();
copy_elements(beg,end);
}
template<class Type>template<class It>void Vector<Type>::copy_elements(It beg,It end)
{
while(beg!=end)
{
push(*beg);
++beg;
}
}
template<class Type>ostream & operator<<(ostream &os,const Vector <Type> &q)
{
os<<"<";
VectorItem<Type>*p;
for(p=q.head;p;p=p->next)
{
os<<p->item<<" ";
}
os<<">"<<endl;
return os;
}
int main()
{
Vector<int>v;
for(int i=0;i<10;i++)
{
v.push_back(i);
}
cout<<v;
return 0;
}