You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中enqueue/dequeue与push/pop的区别及能否混用的疑问

关于队列/栈操作命名的困惑:push/pop vs enqueue/dequeue

网上查到的信息存在矛盾:多数搜索结果说enqueue/dequeue是队列的专属操作,push/pop是栈的专属操作,二者功能不同;但实际在C++ STL里,push/pop同时适用于栈和队列——栈的push是往栈顶添加元素,pop移除栈顶元素;队列的push是往队尾添加元素,pop移除队首元素。那为什么还要用enqueue/dequeue?push/pop能不能和队列操作互换使用?


解答

  • 术语通用性与语言实现的差异
    enqueue/dequeue是数据结构领域的通用标准术语,明确指代队列的"入队/出队"行为;而push/pop最初是栈的专属术语,对应"压栈/弹栈"操作。但C++ STL为了保持容器接口的一致性,给queue也提供了push/pop方法,本质上队列的push就是enqueue,pop就是dequeue,功能完全等价。

  • 为何保留enqueue/dequeue术语?

    • 语义更精准:在跨语言、跨项目的场景下,enqueue/dequeue能直接表明操作对象是队列,避免和栈的push/pop产生语义混淆;
    • 不同实现的规范差异:部分编程语言或第三方库严格遵循经典数据结构命名,只给队列提供enqueue/dequeue,栈用push/pop,不会混用;
    • 代码可读性:在支持enqueue/dequeue的环境中使用该术语,能让其他开发者一眼识别出这是队列操作,无需额外判断容器类型。
  • C++中push/pop与队列操作的关系
    C++ STL的queue容器并没有直接提供enqueue/dequeue方法,而是用push(还有C11新增的emplace)实现入队,用pop实现出队,二者功能和enqueue/dequeue完全一致。所以在C里写队列的入队出队,用push/pop是完全合法且常规的写法,不存在"互换"的问题——它们就是同一操作的不同命名(只是STL选择了复用push/pop这个接口名)。


验证代码

#include <stdio.h>
#include <iostream>
using namespace std;
#include <stack>
#include <queue>

stack<int> CreateStack(int Array[], int length)
{
    stack<int> stk;

    for (int i = 0; i < length; i++)
    {
        stk.push(Array[i]);
    }
    return stk;
}

queue<int> CreateQueue(int Array[], int length)
{
    queue<int> que;

    for(int i = 0; i < length; i++)
    {
        que.push(Array[i]);
    }
    return que;
}


void printStack(stack<int> inputStack)
{
    cout << "栈顶" << endl;
    while(inputStack.empty() == false)
    {
        cout << inputStack.top() << endl;
        inputStack.pop();
    }
    cout << "栈底" << endl;
}

void printQueue(queue<int> inputQueue)
{
    cout << "队首" << endl;
    while(inputQueue.empty() == false)
    {
        cout << inputQueue.front() << endl;
        inputQueue.pop();
    }
    cout << "队尾";
}

int main()
{
    int stackArray[] = {2,4,6,8,10};
    int arraySize = sizeof(stackArray)/sizeof(stackArray[0]);
    stack<int> stk = CreateStack(stackArray, arraySize);
    queue<int> que = CreateQueue(stackArray, arraySize);
    printStack(stk);
    printQueue(que);
}

代码输出

栈顶
10
8
6
4
2
栈底
队首
2
4
6
8
10
队尾

内容的提问来源于stack exchange,提问作者Vultiverse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:40:26