尝试使用堆栈创建队列.为什么我会遇到int转换错误的空白

Trying to create queue using stacks. Why am I getting a void to int conversion error?

本文关键字:int 遇到 转换 错误 空白 为什么 堆栈 队列 创建      更新时间:2023-10-16

这是我第一次使用两个堆栈创建队列的尝试。我不确定我是否在正确的轨道上,因为由于'=': cannot convert from 'void' to 'int'错误,我无法检查工作。错误在于这一行:x = enQ.pop();。ENQ不是一个函数,那么它怎么可能无效?


我的代码尚未完成。

stack<int> enQ;
stack<int> deQ;
void enQueue(int x) {
    enQ.push(x);
    cout << x << " has been added to the queue." << endl;
}
void deQueue() {
    while (enQ.size() != 0) {
        int x;
        x = enQ.pop();
        enQ.pop();
        deQ.push(x);
        cout << x << " had been pushed to DEQUEUE" << endl;
    }
}

因为函数std :: stack :: pop nothing nothing nothing(即其返回类型为 void)。

您可以更改

x = enQ.pop();

to

x = enQ.top();
enQ.pop();

您可以检查此帖子,以了解为什么STL将T kind_of_pop_and_get()分离为poptop。以前只能删除堆栈上的顶部元素,后者只需复制顶部元素而无需接触堆栈即可。

为什么不std :: queue :: pop返回值。?

简而言之,它是例外安全

kind_of_pop_and_get()会做

  • 从堆栈中删除元素。
  • 然后将元素返回接收器的copy assignment/constructor

例外可能会在对象构造过程中抛出,并开始堆栈放松。然后,即使kind_of_pop_and_get()调用未完成,堆栈状态也可能受到影响。