C++,STL容器适配器,queue:队列深入解析

C++,STL容器适配器,priority_queue:优先队列深入解析 std::priority_queue是C++标准模板库(STL)提供的容器适配器,实现优先队列数据结构。元素按优先级排序,队首始终为最大(默认)或最小元素。底层通常基于vector实现堆结构。 阅读详情

请添加图片描述


一、容器概览与核心特性

std::queue是C++标准模板库(STL)提供的容器适配器,遵循先进先出(FIFO)原则。它基于底层容器(默认std::deque)封装实现,为队列操作提供统一接口。


核心特性速览

特性 说明
底层容器 默认deque,可指定list
时间复杂度 push/pop均为O(1)
空间复杂度 与底层容器一致
迭代器支持 ❌ 不支持遍历操作
头文件 <queue>

二、底层实现原理

1. 容器适配器设计

queue通过组合现有容器实现功能,类声明原型:


    template<
        typename T,
        typename Container = std::deque<T>
    > class queue;

支持的可选底层容器需满足以下接口:

  • push_back()

  • pop_front()

  • front()

  • back()

  • empty()

  • size()


2. 默认容器对比

底层容器 优点 缺点
deque 高效头尾操作(默认最优解) 内存非连续
list 稳定删除性能 内存碎片化,缓存不友好

三、核心操作详解

1. 容器初始化


    // 默认使用deque
    queue<int> q1; 

    // 指定底层容器
    queue<string, list<string>> q2;

    // 通过已有容器初始化
    deque<int> dq {
   
   1,2,3};
    queue<int> q3(dq);  // 注意:复制容器内容

2. 元素操作接口


    queue<string> msgQueue;

    // 入队操作
    msgQueue.push("msg1");        // 拷贝插入
    msgQueue.emplace("msg2");     // 原地构造(C++11)

    // 访问首尾元素
    cout << "Front: " << msgQueue.front(); 
    cout << "Back: " << msgQueue.back();

    // 出队操作
    msgQueue.pop();  // 返回void,需先获取front()

    // 容量检查
    if (!msgQueue.empty()) {
   
   
        cout << "Queue size: " << msgQueue.size();
    }

3. 自定义队列实现


    template<typename T, typename Container = deque<T>>
    class ThreadSafeQueue {
   
   
        queue<T, Container> data;
        mutex mtx;
        condition_variable cv;

    public:
        void push(const T& val) {
   
   
            lock_guard
【C++入门到精通】C++入门 —— 容器适配器、stack和queue(STL) stack是一种后进先出(LIFO)的数据结构,它的特点是最后添加的元素将首先被移除。它是一种容器适配器,使用底层容器来存储元素。默认情况下,stack使用std::deque作为底层容器。你可以使用push(element)函数将元素添加到栈顶,使用pop()函数从栈顶移除元素,使用top()函数访问栈顶元素,使用empty()函数检查栈是否为空,使用size()函数获取栈的大小。stack不支持索引访问和迭代器,大小是可变的。 阅读详情

相关推荐

IO多路转接 ——— select、poll、epoll

select是系统提供的一个多路转接接口。select函数的函数原型如下: 参数说明:参数timeout的取值:返回值说明:select调用失败时,错误码可能被设置为:fd_set结构与sigset_t结构类似,fd_set本质也是一个位图,用位图中对应的位来表示要监视的文件描述符。 调用select函数之前就需要用fd_set结构定义出对应的文件描述符集,然后将需要监视的文件描述符添加到文件描述符集当中,这个添加的过程本质就是在进行位操作,但是这个位操作不需要用户自己进行,系统提供了一组专门的接口,用

2021dragon的博客 7990

Windows11开机必看:3种方法跳过联网激活(含最新OOBE命令)

本文详细介绍了Windows11新机开箱时绕过联网激活的三种实用方法,包括任务管理器终止进程法、命令行强制终止法和最新的OOBE\BYPASSNRO命令法。特别推荐使用微软官方预留的OOBE命令,操作简单且无副作用,帮助用户快速完成系统设置。

weixin_28366353的博客 1666

Unity地形优化实战:LOD、合批与HLOD打造流畅开放世界

在计算机图形学与游戏开发中,渲染优化是保障应用流畅运行的核心技术。其基本原理在于通过算法与策略,在视觉保真度与硬件资源消耗之间寻求最佳平衡,旨在提升帧率、降低功耗。这一技术的核心价值在于,它直接决定了大规模场景(如开放世界游戏)在性能受限平台(尤其是移动设备)上的可行性。具体到地形渲染这一关键应用场景,开发者需要综合运用多层次细节(LOD)技术来动态调整模型精度,并通过Draw Call合批(Batching)与GPU实例化(GPU Instancing)来大幅减少CPU到GPU的通信开销。对于超大规模世界

weixin_28077113的博客 342

Ubuntu双系统引导修复实战:boot-repair工具详解

本文详细介绍了使用boot-repair工具修复Ubuntu双系统引导丢失问题的实战方法。当GRUB引导菜单因安装新系统或更新而损坏时,通过制作Ubuntu启动盘进入Live环境,安装并运行boot-repair,可一键完成系统修复引导,自动化执行GRUB重装与配置,解决无法进入Windows或Ubuntu的常见故障。

weixin_29224589的博客 365

Python爬虫实战:高效爬取中国专利数据库的完整指南

在当今信息爆炸的时代,专利数据作为技术创新的重要指标,对企业研发、市场分析和学术研究都具有极高价值。中国作为全球专利申请量最大的国家,其专利数据库包含了海量的技术创新信息。本文将详细介绍如何使用Python最新技术构建一个高效、稳定的中国专利数据库爬虫系统。中国专利数据库主要由国家知识产权局(CNIPA)维护,包含发明专利、实用新型专利和外观设计专利三大类。截至2023年,中国专利数据库已收录超过400万件发明专利和300万件实用新型专利。

2201_76125261的博客 1582

AI Agent的知识蒸馏链:多阶段LLM模型优化

随着大语言模型(LLM)规模的不断扩大,如何在保持模型性能的同时提高其部署效率成为关键挑战。本文旨在探讨通过知识蒸馏技术构建多阶段优化链,实现LLM模型的高效压缩和性能优化。研究范围涵盖从基础理论到实际应用的完整知识蒸馏流程,特别关注AI Agent场景下的特殊需求和解决方案。本文首先介绍知识蒸馏的基本概念和背景,然后详细阐述多阶段蒸馏链的核心原理。接着,我们将深入探讨算法实现细节和数学模型,提供完整的代码示例。最后讨论实际应用、工具资源和未来发展方向。

AI大模型应用之禅 358

一步步教你使用 NVIDIA 推出的全新GPU加速求解器 cuOpt:解锁超高效率的求解体验

未完成

Linshaodan520的博客 878

【51单片机仿真】基于51单片机设计的多功能电子时钟日历(实时时钟闹钟秒表温度检测)系统__资料编号5

该项目是基于单片机的多功能电子时钟系统,集成了时间显示、闹钟设置、秒表功能以及温度显示等功能。主要硬件包括1602液晶显示屏、DS1302时钟芯片、DS18B20温度传感器和蜂鸣器。系统通过按键进行时间和闹钟的设置,并实时显示当前时间和温度。

嵌入式阿齐Archie 2万+

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

贝叶斯统计 [韦来生编]

贝叶斯(Bayes)统计是近几十年来迅速发展起来的数理统计的一个重要分支。贝叶斯方法与经典统计方法的主要不同之处是进行统计推断时除了利用样本信息外,还要利用参数的先验信息,因此可以提高统计推断或统计决策的效果。它在经济、金融、生物、医学、自然科学和社会科学等许多领域具有广泛的应用。贝叶斯方法的研究已渗透到了统计学的几乎所有领域。作者在给中国科学技术大学概率论与数理统计专业本科生开设的“数理统计”课程中有一章专门讲授“贝叶斯方法和统计决策理论”,近十年来也给中国科学技术大学概率统计专业研究生开设过几次“贝叶斯分析”课。本书是在对过去讲稿的内容作了适当的增减和调整的基础上完成的。  本书共分六章。第1章是绪论,介绍了贝叶斯统计的若干基本概念,同时对必要的数理统计的基础知识有重点地作了回顾。第二章介绍了确定先验分布的若干可供选择的方法。第三章介绍了几类常见统计模型参数的后验分布的主要结果和计算方法。第四章和第五章分别介绍了“贝叶斯统计推断”和“贝叶斯统计决策”的内容。第六章介绍了贝叶斯统计计算的若干方法,包括蒙特卡洛方法和马尔可夫链蒙特卡洛(MCMC)方法以及相关统计软件的简介。本书的每一章附右大量的例题和习题,书末附有常用的几个表格和部分习题解答供读者查用。  大约可在54学时内讲授本书的第1章至第六章的主要内容,教师可根据学时需要选讲本书第1章至第六章的部分内容。书中标“*”号的章节可略去不讲,留给读者作为阅读材料。第六章例题中的R代码和部分例题的数据文件等可从作者个人主页下载。  作者在编写本书的过程中参考了J.O.Berger教授的《统计决策论及贝叶斯分析》和茆诗松教授编写的《贝叶斯统计》等书中的一些内容,以及《贝叶斯分析》一书中由张伟平博士编写的有关贝叶斯统计计算的一些内容。在此表示衷心感谢。  本书编写准备过程中,中国科学技术大学统计与金融系的几个研究生帮助完成了本书部分中文的录入和排版,作者对他们的辛勤工作表示真诚的感谢。高等教育出版社为本书的出版给予了大力支持。在此一并致谢。

上一篇: C++,STL容器适配器,stack:栈深入解析
下一篇: Renesas RH850 FDL库介绍
智驾
博客等级 码龄11年 6679粉丝 574原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智驾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值
⌂ 换网址