C++:队列中的第一个字符错误

标签 c++ pointers queue output

我目前正在为学校做一项作业,要求我创建一个队列。它似乎在工作。唯一的问题是在我的队列开头有一个意想不到的字符。我使用 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

我已经为这个问题苦苦思索了一段时间,所以我希望你能对这个问题有所了解!

最佳答案

由于定义了 push()*top_ NOT 在队列中。它是队列末尾之后的一个元素。因此,您应该将 print() 定义为从 top_ - 1 开始迭代。

另外正如@stellarossa 提到的,您应该在递增之前返回 bottom_ 指向的字符。也就是说,

char pop() { return *(bottom_++); }

关于C++:队列中的第一个字符错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20050161/

相关文章:

c++ - 在 C++ : segmentation fault when accessing the returned array 中使用指针的数组

c - C中通过void函数初始化指向结构体的指针

c# - 在 C# 中,为了线程安全使用 Queue.Synchronized 或 lock() 会更好吗?

php - 使用redis在laravel中排队

C# 和 C++ 套接字数据加密

c++ - 将字符串变量从 bash 脚本传递到根宏

c++ - `constexpr` 参数在编译时未知时不调用构造函数

c++ - 使用 strstream C++ 将数字转换为字符串并返回

c - 返回指向字符串数组的指针 C

c++ - std::queue<T, list<T>>::size() 在 O(n) 中很慢?