Array Implementation of Queue: Strange Output - c++

I am learning about queues and I wrote the following program which implements the queue as a linear array (NOT a circular one).
#include<iostream>
using namespace std;
class queue {
int front, max_queue, rear, count = 0;
int *items;
public:
queue(int);
~queue();
void enqueue(int);
void dequeue();
bool isEmpty();
int size();
void display();
};
queue::~queue() {
delete []items;
}
queue::queue(int max) {
front = -1;
rear = -1;
max_queue = max;
items = new int[max_queue];
}
void queue::enqueue(int n) {
if (count == max_queue)
cout << "queue is full, no enqueue possible";
else {
items[++rear] = n;
count++;
}
}
void queue::dequeue() {
if (count == 0)
cout << "no dequeue possible, queue already empty";
else {
front--;
count--;
}
}
bool queue::isEmpty() {
return ((count == 0) ? 1 : 0);
}
int queue::size() {
return count;
}
void queue::display() {
if (count == 0)
cout << "nothing to display";
else {
for (int i = front; i <= rear;)
cout << items[i++] << endl;
}
}
int main() {
queue *qe = new queue(10);
qe->enqueue(1);
qe->enqueue(2);
qe->enqueue(3);
qe->enqueue(4);
qe->display();
return 0;
}
I get the following output
49
1
2
3
4
RUN FINISHED; exit value 0; real time: 10ms; user: 0ms; system: 0ms
Why is there a 49 in my output.? Is it a garbage value? Does not using a circular array implementation,a probable cause?
I have no idea. Any help appreciated.

You're starting the display loop i with front which is -1. You're pointing to a spot before your queue.

If a queue is empty and you enqueue an element x, then x becomes both the front and the rear.

The issue is in your display function:
for (int i = front; i <= rear;)
cout << items[i++] << endl;
You're setting i=front, but you've previously set front=-1. Thus, you're attempting to access items[-1]. You can either set i=front+1:
for (int i = front + 1; i <= rear;)
cout << items[i++] << endl;
or continue until i<rear and use ++i instead of i++:
for (int i = front; i < rear;)
cout << items[++i] << endl;

Related

Circular Queue That has a display function that displays even numbers only

hi so i have this circular queue c++ program i need its display function only displays even inserted numbers only can someone here help please here's the code
i need a way that this program only displays even numbers only i'v been trying to use the %2==0 on some location that might make sense but mostly i get them wrong or empty
.
.
.
.
.
.
#include <iostream>
using namespace std;
int cqueue[5];
int front = -1, rear = -1, n=5;
void insertCQ(int val) {
if ((front == 0 && rear == n-1) || (front == rear+1)) {
cout<<"Queue Overflow \n";
return;
}
if (front == -1) {
front = 0;
rear = 0;
} else {
if (rear == n - 1)
rear = 0;
else
rear = rear + 1;
}
cqueue[rear] = val ;
}
void deleteCQ() {
if (front == -1) {
cout<<"Queue Underflow\n";
return ;
}
cout<<"Element deleted from queue is : "<<cqueue[front]<<endl;
if (front == rear) {
front = -1;
rear = -1;
} else {
if (front == n - 1)
front = 0;
else
front = front + 1;
}
}
void displayCQ() {
int f = front, r = rear;
if (front == -1) {
cout<<"Queue is empty"<<endl;
return;
}
cout<<"Queue elements are :\n";
if (f <= r) {
while (f <= r){
cout<<cqueue[f]<<" ";
f++;
}
} else {
while (f <= n - 1) {
cout<<cqueue[f]<<" ";
f++;
}
f = 0;
while (f <= r) {
cout<<cqueue[f]<<" ";
f++;
}
}
cout<<endl;
}
int main() {
int ch, val;
cout<<"1)Insert\n";
cout<<"2)Delete\n";
cout<<"3)Display\n";
cout<<"4)Exit\n";
do {
cout<<"Enter choice : "<<endl;
cin>>ch;
switch(ch) {
case 1:
cout<<"Input for insertion: "<<endl;
cin>>val;
insertCQ(val);
break;
case 2:
deleteCQ();
break;
case 3:
displayCQ();
break;
case 4:
cout<<"Exit\n";
break;
default: cout<<"Incorrect!\n";
}
} while(ch != 4);
return 0;
}
Here's a quick example using std::queue:
#include <iostream>
#include <queue>
int main()
{
// This deque is declared just to more easily instantiate the queue
std::deque<int> deck{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::queue<int> q{deck};
while (!q.empty()) {
if (q.front() % 2 == 0) {
std::cout << q.front() << ' ';
}
q.pop();
}
std::cout << '\n';
}
You were on the right path using mod 2, but everything about your "queue" is not correct. To put it simply, you have not written a queue, and definitely not a circular queue.
Queues are FIFO data structures; first in, first out. Think of it like a tunnel. I will only add elements to one end, and I will only remove elements from the other. Everything in the middle does not matter, except to know the size of the queue. This means that the only visible elements are the first and last. If I want to see the second element of the queue, I must remove the first element.
The code you've written treats your array like a list instead where you have free access to all elements.
It's better to write an actual queue class, and I would hope that if you're writing data structures, that you are able to write a class.
Here's an extremely basic queue class that exhibits the behavior you are asking about. There is nothing circular about it. The word circular implies that your queue should be implemented with a circular linked list and not an array. It's worth noting that it requires at least C++11, but that really shouldn't be a problem today.
IMPORTANT
This code leaves out a lot of necessary error-checking. For example, back() will likely lead to undefined behavior if called on an empty queue, among other things. This was intentional to avoid a flat-out copy/paste being employed because cheating on homework is bad.
#include <array>
#include <iostream>
namespace Q {
class queue {
public:
int &front() { return m_arr[0]; }
int &back() { return m_arr[m_size - 1]; }
void push(int val) {
if (m_size < 5) {
m_arr[m_size] = val;
++m_size;
}
}
// Shifts entire array one to the left
void pop() {
if (m_size > 0) {
for (int i = 1; i < m_size; ++i) {
m_arr[i - 1] = m_arr[i];
}
--m_size;
}
}
bool empty() const { return m_size == 0; }
private:
std::array<int, 5> m_arr = {0};
int m_size = 0;
};
}; // namespace Q
int main() {
Q::queue q;
for (int i = 1; i <= 5; ++i) {
q.push(i);
}
while (!q.empty()) {
if (q.front() % 2 == 0) {
std::cout << q.front() << ' ';
}
q.pop();
}
std::cout << '\n';
}

C++ Strange behavior in my own stack class

Here is a program with my Stack class and some another functions.
ReadTheFile() - reads numbers, which are stored in num_file.txt, and returns a vector with those numbers.
IntervalCheck() - adds the numbers of the specific range from input vector and returns a vector with those numbers only.
VecToMyStack() - adds numbers from a vector to a stack.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#define STACK_EMPTY -1
#define OUT_OF_STACK -2
using namespace std;
template <class T>
class Stack {
private:
struct Node{
T element;
Node *prevElement;
};
size_t NumberOfElements;
Node *tempAdr;
Node *topElement;
Node *newElement;
Node *erasedElement;
public:
Stack(){
topElement = new Node;
topElement->prevElement = nullptr;
NumberOfElements = 0;
}
~Stack(){
cout << endl << "I'm a destructor";
while(NumberOfElements !=0 ){
tempAdr = topElement->prevElement;
delete topElement;
topElement = tempAdr;
NumberOfElements--;
}
delete topElement;
}
void push(T input_element){
tempAdr = topElement;
topElement = new Node;
topElement->element = input_element;
topElement->prevElement = tempAdr;
NumberOfElements++;
}
void pop(){
if (NumberOfElements == 0) throw STACK_EMPTY;
else {
tempAdr = topElement->prevElement;
delete topElement;
topElement = tempAdr;
NumberOfElements--;
}
}
T top(){
return NumberOfElements != 0 ? topElement->element : throw STACK_EMPTY;
}
void insert(size_t position, T input_element){
if (position >= NumberOfElements) throw OUT_OF_STACK;
else {
tempAdr = topElement;
for (size_t i = 0; i < position; i++){
tempAdr = tempAdr->prevElement;
}
newElement = new Node;
newElement->element = input_element;
newElement->prevElement = tempAdr->prevElement;
tempAdr->prevElement = newElement;
NumberOfElements++;
}
}
void erase(size_t position){
if (position >= (NumberOfElements-1)) throw OUT_OF_STACK;
else{
tempAdr = topElement;
for (size_t i = 0; i < position; i++){
tempAdr = tempAdr->prevElement;
}
erasedElement = tempAdr->prevElement;
tempAdr->prevElement = tempAdr->prevElement->prevElement;
delete erasedElement;
NumberOfElements--;
}
}
void print(){
if (NumberOfElements != 0){
tempAdr = topElement;
for (size_t i = 0; i < NumberOfElements; i++){
cout << tempAdr->element << " ";
tempAdr = tempAdr->prevElement;
}
}
}
size_t size() { return NumberOfElements; }
};
vector<int> ReadTheFile() {
vector<int> vec_from_file;
int buffer;
ifstream basefile;
basefile.open("num_file.txt", ios::in);
if (basefile.is_open()) {
do {
if (basefile >> buffer)
vec_from_file.push_back(buffer);
else {
basefile.clear();
basefile.ignore(1, ' ');
}
} while (!basefile.eof());
basefile.close();
}
else cout << "Unable to open file" << endl;
return vec_from_file;
}
vector<int> IntervalCheck(vector<int> vec_for_check){
vector<int> out_vec;
if (vec_for_check.empty()) cout << "There is nothing to check";
else {
int begin_int, end_int;
do {
cin.clear();
cin.sync();
cout << "Input the first and the last value of the interval: ";
cin >> begin_int >> end_int;
} while (cin.fail());
for (auto &k : vec_for_check)
if (k > begin_int && k < end_int)
out_vec.push_back(k);
}
return out_vec;
}
Stack<int> VecToMyStack(vector<int> input_vec){
Stack<int> output_st;
if (input_vec.empty()) {
cout << "the end";
}
else {
for (auto &k : input_vec){
output_st.push(k);
}
}
return output_st;
}
int main(){
int choice = 0;
do {
cin.clear();
cin.sync();
VecToMyStack(IntervalCheck(ReadTheFile())).print();
cout << "Would you like to measure another interval? 1-yes 2-no";
cin >> choice;
} while (choice == 1);
system("pause");
return 0;
}
The whole program should push numbers from the file to a stack, and print this stack, using the print() method of the class. For example, if there is a num_file.txt with
0 1 2 3 4 5 6 7 8 9 10
inside, the program is expected to work in that way:
Input the first and the last value of the interval: 0 10 /* zero and
ten are inputed by the user*/
1 2 3 4 5 6 7 8 9
Would you like to measure another interval? 1-yes 2-no
But when the VecToMyStack(IntervalCheck(ReadTheFile())).print(); line is executed, I'm getting
Access violation reading location 0xFEEEFEEE.
exception. It seemes like the destructor of my Stack class is running before the print()function. Why does that happen? Is there something special what I should add to my Stack class or to VecToMyStack() function?
Finally, after a couple of hours of research, I've got that missing peace of code:
Stack(const Stack &object){
tempAdr = object.topElement;
T * tempMas=new T[object.NumberOfElements];
for (size_t i = 0; i < object.NumberOfElements; i++){
tempMas[i] = tempAdr->element;
tempAdr = tempAdr->prevElement;
}
topElement = new Node;
topElement->prevElement = nullptr;
NumberOfElements = 0;
for (int i = object.NumberOfElements - 1; i >= 0; i--){
push(tempMas[i]);
}
delete[] tempMas;
}
I know that my Stack class is still uncomplete without the overloaded assignment operator, but at least my code runs fine.

C++ Stack values not working correctly

I am trying to implement a system that would perform something like say the user enters 4 5 +. It would add the 4 and 5 (9) and push 9 into the stack.
For some reason the values in the stack are huge numbers so I believe it has something to do with a pointer or accessing a wrong field but I'm pulling my hair out trying to find the error. Any help on what I'm doing wrong?
#include "stack.h"
int main()
{
stack Test;
bool stop = false;
float runningtotal = 0;
while (stop == false)
{
char input;
cin >> input;
if (input == '+') {
int value1 = Test.top();
Test.pop();
int value2 = Test.top();
Test.pop();
cout << value1+value2 << endl;
Test.push(value1 + value2);
}
cout << Test.top();
std::getchar();
std::getchar();
}
And the implementation of stack
#include "stack.h"
stack::stack()
{
maxsize = MaxSize;
currentsize = 0;
sptr = new StackElement[maxsize];
}
stack::~stack()
{
delete [] sptr;
}
void stack::push(StackElement data)
{
if (currentsize < maxsize)
{
sptr[currentsize] = data;
currentsize++;
} else {
cout << "Stack is full ;-;";
}
}
void stack::pop()
{
if (currentsize == 0) {
cout << "Empty stack? ;-;";
return;
}
currentsize--;
}
StackElement stack::top()
{
if (currentsize == 0) {
cout << "Empty stack u ninja ;-;";
return NULL;
} else {
return (sptr[currentsize]);
}
}
void stack::push(StackElement data)
{
if (currentsize < maxsize)
{
sptr[currentsize] = data;
currentsize++; //<--- incrementing after so nothing in [currentsize] now
} else {
cout << "Stack is full ;-;";
}
}
StackElement stack::top()
{
if (currentsize == 0) {
cout << "Empty stack u ninja ;-;";
return NULL;
} else {
return (sptr[currentsize]);// should use currentsize-1
// latest filled cell
// since its pushing from top
}
}
Be sure to convert those ascii codes(49 ish) from keyboard to integer type explanations.
input - 48 should do it.

C++ Circular queue class with a length of 100

I've got some questions on how to create and use a circular queue class in C++. The questions are in the code as comments because I am looking for general pointers on how to see if I'm on the right track.
Edit:
Adding the specific questions here for clarity:
Do I need a pointer for both the head and the tail of the queue?
Do I initialize a queue like this or is there a better way?
How do I dequeue and return the correct value?
The code:
#include <iostream>
#include <stdexcept>
using namespace std;
class Queue{
private:
int maxSize;
int *data; // Do I maybe need one for head and one for tail?
int counter; // Used to count the amount of elements in the queue.
public:
Queue();
Queue(int max=100);
~Queue();
void clear();
bool empty() const;
bool full() const;
int dequeue() throw (length_error);
void enqueue(int value) throw (length_error);
int length();
};
Queue :: Queue() // Is this the correct way to initialize the queue?
{
data[100];
counter = 0;
maxSize = 100;
}
void Queue::clear()
{
data = NULL;
}
bool Queue::empty()const
{
if(counter == 0)
return true;
return false;
}
bool Queue::full()const
{
if(counter == 100)
return true;
return false;
}
int Queue::length()
{
return counter;
}
int Queue::dequeue() throw (length_error) // How do I get the correct element and then return it.
{
if(counter >= 0)
{
counter--;
return counter;
}
return counter;
}
void Queue::enqueue(int value) throw(length_error)
{
if(counter < maxSize)
{
data[counter] = value;
counter++;
cout << "Adds the number at the end if there is room for it." << endl;
}
else
;// throw(length_error);
}
int main()
{
Queue minQueue;
minQueue.enqueue(10);
minQueue.enqueue(12);
minQueue.enqueue(14);
minQueue.enqueue(16);
minQueue.enqueue(18);
cout << "Empty: " << minQueue.empty() << endl;
cout << "Full: " << minQueue.full() << endl;
cout << "Length: " << minQueue.length() << endl;
minQueue.dequeue();
minQueue.clear();
system("pause");
}
Your code has some issues.
class Queue{
// ...
public:
// Queue(); // deleted this line, since it collides with the next ctor declation.
// A ctor with one optional argument includes a ctor with no arguments
Queue(int max=100);
~Queue();
}
//...
Queue::Queue(int max) // argument required!
{
data = new int[max]; // this is probably what you want
counter = 0;
maxSize = max;
}
void Queue::clear()
{
delete[] data; // see above, must match the allocation
}
int Queue::dequeue() throw (length_error)
{
if(counter > 0) // !!!! dont't decrease when 0
{
counter--;
return data[counter];
}
else
throw(length_error()); // an exception class length_error must exist!
}
These are a few starting points, fill the remaining gaps by yourself.

Trouble with Array Lists And Using the Insert and Retrieve Functions Given (Segment Core Dump)

I am having difficuly implementing a few functions in my array list.
I want to use the predefined function "insert" to insert a value into the list. I then want to use the retrieve function to print out the values of the entire list.
However, when I test my function, the program exits with a segmentation core dump after the last value is inserted
Any help would be appreciated.
Header:
/** #file ListA.h */
#include <string>
using namespace std;
const int MAX_LIST = 0;
typedef string ListItemType;
class List
{
public:
List();
bool isEmpty() const;
int getLength() const;
void insert(int index, const ListItemType& newItem, bool& success);
void retrieve(int index, ListItemType& dataItem, bool & success) const;
void remove(int index, bool& success);
List selectionSort(List selectList);
private:
ListItemType items[];
int size;
int translate(int index) const;
};
Implementation:
/** #file ListA.cpp */
#include "ArrayList.h" // header file
#include <iostream>
#include <fstream>
List::List() : size()
{
}
bool List::isEmpty() const
{
return size == 0;
}
int List::getLength() const
{
return size;
}
void List::insert(int index, const ListItemType& newItem, bool& success)
{
success = (index >= 1) &&
(index <= size + 1) &&
(size < MAX_LIST);
if (success)
{
for (int pos = size; pos >= index; --pos)
items[translate(pos + 1)] = items[translate(pos)];
items[translate(index)] = newItem;
++size;
}
}
void List::remove(int index, bool& success)
{
success = (index >= 1) && (index <= size);
if (success)
{
for (int fromPosition = index + 1;
fromPosition <= size;
++fromPosition)
items[translate(fromPosition - 1)] = items[translate(fromPosition)];
--size; // decrease the size of the list by one
} // end if
} // end remove
void List::retrieve(int index, ListItemType& dataItem,
bool& success) const
{
success = (index >= 1) && (index <= size);
if (success)
dataItem = items[translate(index)];
}
int List::translate(int index) const
{
return index - 1;
}
List List::selectionSort(List selectList)
{
return selectList;
}
int main()
{
ListItemType insertType = "listItem1";
ListItemType retrieveType = "listitem2";
int numberofitems;
cout << "Please enter the number of data items:" << endl;
cin >> numberofitems;
cout << endl;
cout << "Please enter the data items, one per line:" << endl;
int listofitems[numberofitems];
List myArrayList;
cout << myArrayList.getLength() << endl;
if (myArrayList.isEmpty()) // tests before
{
cout << "This list is empty \n" << endl;
}
else
{
cout << "List is not empty! \n"<< endl;
}
bool mainsucc = true;
for (int i = 0; i<numberofitems; i++)
{
cout << "Enter number " << i + 1 << " : " << endl;
cin >> listofitems[i];
}
for (int i =0; i <numberofitems; i++){
myArrayList.insert(listofitems[i], insertType, mainsucc);}
cout << "Size of the list is : " << myArrayList.getLength() << endl;
/*for (int i=0; i<mainarraylistsize; i++)
{
cout << myArrayList.retrieve(listofitems[i], retrieveType, mainsucc);
}*/
if (myArrayList.isEmpty()) // tests after
{
cout << "This list is empty \n" << endl;
}
else
{
cout << "List is not empty! \n"<< endl;
}
return 1;
}
have MAX_LIST == 0 means that success will always be false in your insert function.