C++ Queues Part 2

Published on: November 4, 2011

In my last tutorial, I introduced queues to you and what I would be doing to teach you C++ Queues. This is the second part of the C++ Queues video series. In this tutorial, I show you how to use the functions highlighted in the first part. This also sets you up for the third part of C++ Queues where I will use #include queue and show you how to make this program much shorter because all you'll need is a few commands.

If you have any questions about the program or anything in general relating to beginner C++ Programming, feel free to ask.

Remember to checkout the Codesnip below to review the C++ code yourself! Feel free to copy the code, but I ask that you please provide credit if you leave the code unchanged when you use it.

Codesnip:

//Programmer:	Nazmus
//Program:		Coding C++ Queues
//Website:		EasyProgramming.net

#include <iostream>

#include <string>
using namespace std;

const int maxqueue = 7;

struct queuetype
{
	string name[maxqueue];
	int front;

	int back;
};

void createqueue(queuetype &queue);
bool fullqueue(queuetype queue);

bool emptyqueue(queuetype queue);
void enqueue(queuetype &queue, string &newelement);

void dequeue(queuetype &queue, string &nameout);

int main()
{

	queuetype students;
	string newelement, nameout;
	char quest;

	createqueue(students);

	cout << "Do you want to enter data (Y/N)? ";
	cin >> quest; 

	while ((quest=='y' || quest=='Y') && (!(fullqueue(students))))
	{

		cout << "Enter name: ";
		cin >> newelement;

		enqueue(students, newelement);

		if(!(fullqueue(students)))
		{
			cout << "Do you want to enter data (Y/N)? ";
			cin >> quest; 
		}
	}

	while(!(emptyqueue(students)))
	{
		dequeue(students, nameout);

		cout << nameout << endl;
	}


	cin.get();

	cin.ignore();
	//system("pause");
}

void createqueue(queuetype &queue)
{

	queue.front = maxqueue - 1;
	queue.back = maxqueue - 1;
}

bool fullqueue(queuetype queue)
{
	if(queue.front == (queue.back +1) % maxqueue ) return 1;

	else return 0;

}

void enqueue(queuetype &queue, string &newelement)
{

	queue.back = (queue.back + 1) % maxqueue;

	queue.name[queue.back] = newelement;
}

bool emptyqueue(queuetype queue)
{

	if(queue.front == queue.back) return 1;

	else return 0;
}

void dequeue(queuetype &queue, string &nameout)
{

	queue.front = (queue.front +1) % maxqueue;

	nameout = queue.name[queue.front];
}



Comments: