Jump to content
  • Advertisement
Sign in to follow this  
JackChurch

queue class details

This topic is 3298 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!