Sign in to follow this  
JackChurch

queue class details

Recommended Posts

here is a simple queue program I just want to know why the location indices need to be incremented before the data is put into and retrieved from the array that holds the queue kind regards Jack
#include <iostream>
using namespace std;

const int maxQsize = 100;

//creating a template queue class
template<class Qtype>class Queue {
	Qtype q[maxQsize];//array to hold queue data
	int size;
	int putloc, getloc;//location indices
public:
	//constructor
	Queue(int len){
		if(len>maxQsize) len = maxQsize;
		else if(len<=0) len = 0;
		size = len;
		putloc = getloc = 0;
	}

	//put data into the queue
	void put(Qtype data){
		if(putloc == size){
			cout << " -- Queue is full.\n";
		return;
		}
		
		putloc++;//why not put entry in location 0?
		q[putloc]=data;//put data into array
	}

	//get data from queue
	Qtype get(){
		if(getloc==putloc){
			cout << " -- Queue is empty.\n";
			return 0;
		}

		getloc++;
		return q[getloc];//get data from queue
	}
};

int main(){
	Queue<int> iQ(10);
	Queue<char> cQ(10); //create 2 integer queues.

	iQ.put(1);
	iQ.put(2);
	iQ.put(3);

	cQ.put('x');
	cQ.put('y');
	cQ.put('z');

	cout << "Contents of integer queue iQ: ";
	for(int i=0; i<3; i++)
		cout << iQ.get() << " ";
		cout << endl;

	cout << "Contents of character queue cQ: ";
	for(int i=0; i<3; i++)
		cout << cQ.get() << " ";
		cout << endl;

	cin.get();
	cin.get();
	return 0;
}

Share this post


Link to post
Share on other sites
This implementation is bugged and invokes undefined behavior by accessing one element past the allocated memory.

In a typical compiler implementation, filling up the queue, will cause last element put into queue to overwrite the size member. Either way, what happens when trying to put an element into a queue with just one remaining space is undefined.

get() is also similarly bugged, and it's hard to say what exactly it's supposed to do.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this