using System;
/*
例5-2
文字型データ用のQueueクラス
*/
class SimpleQueue<T>
{
public T[] q; // キューのデータを保持する配列
public int putloc, getloc; // put操作やget操作用の添え字
public SimpleQueue(int size) {
q = new T[size + 1]; // キュー用にメモリを確保する
putloc = getloc = 0;
}
// 1文字分だけキューに追加する
public void Put(T obj) {
if (putloc == q.Length - 1)
{
Console.WriteLine(" -- Queue is full.");
return;
}
putloc++;
q[putloc] = obj;
}
// キューから1文字分だけ取り出す
public T Get()
{
if (getloc == putloc)
{
Console.WriteLine(" -- Queue is empty.");
throw new Exception();
}
getloc++;
return q[getloc];
}
}
// Queueクラスを使う
class QDemo
{
static void Main()
{
SimpleQueue<char> bigQ = new SimpleQueue<char>(100);
SimpleQueue<int> smallQ = new SimpleQueue<int>(5);
char ch;
int i;
Console.WriteLine("Using bigQ to store the alphabet.");
// bigQにいくつかの文字を追加する
for (i = 0; i < 26; i++)
bigQ.Put((char)('A' + i));
// bigQから取り出して表示する
Console.Write("Contents of bigQ: ");
for (i = 0; i < 26; i++)
{
ch = bigQ.Get();
if (ch != (char)0) Console.Write(ch);
}
Console.WriteLine("\n");
Console.WriteLine("Using smallQ to store integer.");
// smallQを使ってエラーを起こさせる
for (i = 0; i < 5; i++)
{
Console.Write("Attempting to store " + i);
smallQ.Put(i);
Console.WriteLine();
}
Console.WriteLine();
// さらにsmallQでエラーを起こさせる
Console.Write("Contents of smallQ: ");
int g;
for (i = 0; i < 5; i++)
{
g = smallQ.Get();
Console.Write(g);
}
}
}
本では、エラー処理含めての例題になってますが、自分はジェック型クラスの取り扱い方のみで、例題を参考にして打ち込んでみました。何度かやって見ないと分からないですね。Getではqueueが空の場合、throw new Exception();してます。リターン値があるのですが、出来ない場合もあります。throwするとreturnが無くても良いようです。