【发布时间】:2013-11-18 14:26:22
【问题描述】:
我目前正在为学校做一个作业,说我应该创建一个队列。它似乎正在工作。唯一的问题是我的队列开头有一个意外的字符。我使用 CQueue 类从队列中推送和弹出值。我必须使用这个类而不是 std::queue 或 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";
}
这是我的主要方法:
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;
当我运行此代码时,队列被填满,但 *bottom_ 被替换为 '=' 符号。这是我的输出:
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
我一直在努力解决这个问题,所以我希望你能对这个问题有所了解!
【问题讨论】: