📄 pex5_1.cpp
字号:
#include <iostream.h>
#include <stdlib.h>
#include <fstream.h>
typedef double DataType;
// maximum size of a queue list
const int MaxQSize = 50;
class Queue
{
private:
// queue array and its parameters
int front, rear, count;
DataType qlist[MaxQSize];
public:
// constructor
Queue (void); // initialize integer data members
// queue modification operations
void QInsert(const DataType& item);
DataType QDelete(void);
void ClearQueue(void);
// queue access
DataType QFront(void) const;
// queue test methods
int QLength(void) const;
int QEmpty(void) const;
int QFull(void) const;
void QPrint(void);
};
// initialize queue front, rear, count
Queue::Queue (void) : front(0), rear(0), count(0)
{}
// insert item into the queue
void Queue::QInsert (const DataType& item)
{
// terminate if queue is full
if (count == MaxQSize)
{
cerr << "Queue overflow!" << endl;
exit(1);
}
// increment count, assign item to qlist and update rear
count++;
qlist[rear] = item;
rear = (rear+1) % MaxQSize;
}
// delete element from front of queue and return its value
DataType Queue::QDelete(void)
{
DataType temp;
// if qlist is empty, terminate the program
if (count == 0)
{
cerr << "Deleting from an empty queue!" << endl;
exit(1);
}
// record value at the front of the queue
temp = qlist[front];
// decrement count, advance front and return former front
count--;
front = (front+1) % MaxQSize;
return temp;
}
// return value of the first entry
DataType Queue::QFront(void) const
{
return qlist[front];
}
// return number of queue elements
int Queue::QLength(void) const
{
return count;
}
// test for an empty queue
int Queue::QEmpty(void) const
{
// return the logical value count == 0
return count == 0;
}
// test for a full queue
int Queue::QFull(void) const
{
// return the logical value count == MaxQSize
return count == MaxQSize;
}
// clear the queue by resetting count, front and rear to 0
void Queue::ClearQueue(void)
{
count = 0;
front = 0;
rear = 0;
}
void Queue::QPrint()
{
// index moves circularly through the queue
int index = front;
int i = 1;
// print each of the count elements in the queue
while (i <= count)
{
cout << qlist[index] << " ";
// every 8th element, generat a new line
if (i % 8 == 0)
cout << endl;
// move to next queue element
index = (index + 1) % MaxQSize;
i++;
}
}
void main(void)
{
ifstream fin;
double item;
Queue Q;
fin.open("pq.dat", ios::in | ios::nocreate);
if (!fin)
{
cerr << "File 'pq.dat' cannot be opened." << endl;
exit(1);
}
// read the 20 double values from 'pq.dat' and insert
// each into Q
for (int i = 0; i < 20; i++)
{
fin >> item;
Q.QInsert(item);
}
cout << endl;
// test the method QPrint
Q.QPrint();
}
/*
<Run>
<file 'pq.dat'>
1 2 3 4 5 6 7 8 10
20 30 40 50 60 70 80
1.5 2.5 3.5 4.5
1 2 3 4 5 6 7 8
10 20 30 40 50 60 70 80
1.5 2.5 3.5 4.5
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -