#include <iostream>
#include <vector>
using namespace std; template <class Type> class Queue;
template <class T > ostream & operator << (ostream &os, const Queue<T> &); template <class Type> class QueueItem {
friend class Queue<Type >;
friend ostream & operator << <Type> (ostream &os, const Queue<Type> &);
//private class
QueueItem(const Type &val) : Item(val), next() {}
Type Item;
QueueItem<Type > *next;
}; template <class Type> class Queue {
friend ostream & operator << <Type> (ostream &os, const Queue<Type> &); public:
Queue() : head(), tail() {}
template <class It> Queue(It _beg, It _end) : head(), tail() { copy_elems(_beg, _end); }
Queue(const Queue<Type> &Q) : head(), tail() { copy_elems(Q); }
Queue& operator = (const Queue &Q);
~Queue() { Destroy(); }
template <class Iter> void _assign(Iter, Iter);
Type &_front() { return head->Item; }
const Type &_front() const { return head->Item; }
void _push(const Type&);
void _pop();
bool _empty() const { return head == ; } private:
QueueItem<Type> *head;
QueueItem<Type> *tail;
void Destroy();
void copy_elems(const Queue<Type> &);
template <class Iter> void copy_elems(Iter, Iter);
}; template <class Type> Queue<Type>& Queue<Type>::operator = (const Queue<Type> &q)
{
if (this != &q) {
head = tail = ;
for (QueueItem<Type> *pt = q.head; pt; pt= pt->next) {
_push(pt->Item);
}
}
return *this;
} template <class Type> void Queue<Type>::copy_elems(const Queue<Type> &q)
{
for (QueueItem<Type> *pt = q.head; pt; pt = pt->next) {
_push(pt->Item);
}
}
template <class Type> template <class Iter> void Queue<Type>::copy_elems(Iter _beg, Iter _end)
{
while (_beg != _end) {
_push(*_beg);
++_beg;
}
} template <class Type> template <class Iter> void Queue<Type>::_assign(Iter _beg, Iter _end)
{
head = tail = ;
copy_elems(_beg, _end);
} template <class Type> void Queue<Type>::_push(const Type& val)
{
QueueItem<Type> *p = new QueueItem<Type>(val);
if (_empty()) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
} template <class Type> void Queue<Type>::_pop()
{
QueueItem<Type> *p = head;
head = head->next;
delete p;
} template <class Type> ostream & operator << (ostream &os, const Queue<Type> &q)
{
for (QueueItem<Type> *pt = q.head; pt; pt = pt->next) {
os << pt->Item << " ";
}
os << endl;
return os;
} template <class Type> void Queue<Type>::Destroy()
{
while (!_empty()) _pop();
} int main()
{
Queue<int >que;
que._push();
que._push();
que._push();
que._push();
cout << que;
que._pop();
cout << que;
Queue<int >q2, q1(que);
cout << q1;
cout << q2._empty() << endl;
q2 = q1;
cout << q2;
while (!que._empty()) {
cout << que._front() << endl;
que._pop();
}
vector<int > vet(, );
for (int i = ; i < (int)vet.size(); i++) {
cout << vet[i] << ' ';
}
cout << endl;
que._assign(vet.begin(), vet.end());
cout << que;
return ;
}

类模板Queue的实现-LMLPHP

05-11 08:14