队列(queue)c++

本文详细介绍了C++中的队列(Queue)数据结构,包括其基本概念、构造函数、容量检查、元素访问与修改以及示例代码。展示了如何创建、操作和检查队列的状态。
摘要由CSDN通过智能技术生成

定义

C++ 中的队列(queue)是一种先进先出(FIFO)的数据结构。

api

  1. 构造函数

    • queue(): 创建一个空队列。
    • explicit queue(const Container& cont): 使用容器 cont 中的元素构造一个队列。
    • queue(const queue& other): 复制构造函数,创建一个与另一个队列 other 完全相同的队列。
  2. 赋值和交换

    • operator=(): 将另一个队列的内容赋值给当前队列。
    • swap(): 交换两个队列的内容。
  3. 容量

    • empty(): 检查队列是否为空。
    • size(): 返回队列中元素的数量。
  4. 访问元素

    • front(): 返回队列中第一个元素的引用。
    • back(): 返回队列中最后一个元素的引用。
  5. 修改容器

    • push(const T& value): 在队尾添加一个元素。
    • pop(): 移除队首元素。
    • emplace(Args&&... args): 在队尾就地构造一个元素。
    • emplace_front(Args&&... args): 在队首就地构造一个元素。

示例

#include <iostream>
#include <queue>

int main() {
    // 创建一个空队列
    std::queue<int> myQueue;

    // 向队列中添加元素
    myQueue.push(1);
    myQueue.push(2);
    myQueue.push(3);

    // 访问队列中的第一个元素
    std::cout << "Front element of the queue: " << myQueue.front() << std::endl;

    // 移除队列中的第一个元素
    myQueue.pop();

    // 访问队列中的最后一个元素
    std::cout << "Back element of the queue: " << myQueue.back() << std::endl;

    // 检查队列是否为空
    if (!myQueue.empty()) {
        std::cout << "Queue is not empty." << std::endl;
    } else {
        std::cout << "Queue is empty." << std::endl;
    }

    // 输出队列中的元素数量
    std::cout << "Number of elements in the queue: " << myQueue.size() << std::endl;

    return 0;
}

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值