I'm currently working on an assignment for school that says I should create a Queue. It seems to be working. The only problem is that there is an unexpected char at the beginning of my Queue. I use class CQueue to push and pop values from the queue. It is essential that I use this class instead of something like std::queue or deque.
class CQueue
{
private:
char *bottom_;
char *top_;
int size_;
public:
CQueue(int n = 20){
bottom_ = new char[n];
top_ = bottom_;
size_ = n;
}
void push(char c){
*top_ = c;
top_++;
}
int num_items() {
return (top_ - bottom_ );
}
char pop(){
bottom_++;
return *bottom_;
}
void print(){
cout << "Queue currently holds " << num_items() << " items: " ;
for (char *element=top_; element > bottom_; element--) {
cout << " " << *element;
}
cout << "\n";
}
This is my main method:
int main(){
CQueue q(10);
q.push('s');q.push('t');q.push('a');q.push('c');q.push('k');
q.print();
cout << "Popped value is: " << q.pop() << "\n";
q.print();
q.push('!');
q.push('?');
cout << "Popped value is: " << q.pop() << "\n";
q.print();
while (!q.empty()) q.pop();
if (q.num_items() != 0) {
cout << "Error: Stack is corrupt!\n";
}
q.print();
cout << "End of program reached\n"<< endl;
return 0;
When I run this code the queue gets filled but *bottom_ is replaced with a '=' symbol. This is my output:
Queue currently holds 5 items: ═ k c a t
Popped value is: t
Queue currently holds 4 items: ═ k c a
Popped value is: a
Queue currently holds 5 items: ═ ? ! k c
Queue currently holds 0 items:
End of program reached
I've been banging my head over this one for a while now so I hope that maybe you can shed some light on this problem!