当前位置:网站首页>《STL適配器》stack和queue
《STL適配器》stack和queue
2022-07-23 06:54:00 【李逢溪】
一、本篇目的
1、介紹STL六大組件之一--適配器
2、用list和vector實現stack和queue
二、什麼是適配器?
適配器是一種設計模式(設計模式是一套被反複使用的、多數人知曉的、經過分類編目的、代碼設計經驗的總結),該種模式是將一個類的接口轉換成客戶希望的另外一個接口。簡單來說,適配器其實就是我們寫代碼時的一個好的設計方式。比如我們要寫一個棧,我們可以直接用vector或者list做底層來實現。
三、實現stack
template<class T, class Con = deque<T>> class stack { public: void push(const T& x) { _c.push_back(x); } void pop() { assert(!empty()); _c.pop_back(); } bool empty() { return _c.empty(); } size_t size() { return _c.size(); } const T& top() { return _c.back(); } private: Con _c; };
四、實現隊列
template<class T, class Con = deque<T>> class queue { public: void push(const T& x) { _c.push_back(x); } void pop() { _c.pop_front(); } size_t size() { return _c.size(); } bool empty() { return _c.empty(); } const T& front() { return _c.front(); } const T& back() { return _c.back(); } private: Con _c; };
五、可以用vector做隊列的底層嗎?
void test1() { queue<int, vector<int>> s; s.push(1); s.push(2); s.push(3); s.push(4); while (!s.empty()) { cout << s.front() << endl; s.pop(); } }
答:vector不能做queue的底層,因為queue需要pop_front(),而vector並沒有該接口,只有erase接口。
六、為什麼STL裏的stack和queue都是默認使用deque這樣的容器?
這裏需要介紹以下deque,deque是double queue的縮寫,它通常被稱作雙端隊列,因為它在兩端的插入删除效率很高,而隊列和棧正需要的就是兩端插入删除效率高的容器,因此deque常做stack和queue的底層容器。關於deque的底層是如何設計與實現的,我會專門出一篇來闡述deque的設計與實現。
边栏推荐
- 在 MySQL 中使用枚举的陷阱一定要注意!
- Drawing dumbbell diagram with R language
- Support swiftui! Swift image & Video Browser jfherobrowser is online
- 【机器学习】模型选择(性能度量)原理及实战
- 2022备忘录
- 电商项目如何解决线上优惠券超发(排错+解决方案)(荣耀典藏)
- Day27 operation
- 一篇搞定CAS,深度讲解,面试实践必备
- OWA email system login two factor authentication (SMS authentication) scheme
- 使用mediapipe和OpenCV实现摄像头实时人脸检测
猜你喜欢

Alibaba cloud disk IOS / Android version 3.8.0 update, video can be cached according to the definition

ZLMediaKit尝试解决GB28181(UDP方式)的视频花屏问题

中年危机提前来临的一代人,还能够从容生活吗?

电商项目如何解决线上优惠券超发(排错+解决方案)(荣耀典藏)

Test how to use Fiddler to connect the mobile packet capturing app

OpenCV-一维频域滤波器

一篇搞定CAS,深度讲解,面试实践必备

使用mediapipe和OpenCV 实现简单人脸检测

如何打包你的项目并且可以让别的用户通过pip安装

Data warehouse: Exploration and practice of integrating flow and batch
随机推荐
BGP basic configuration and route aggregation
听书项目开发过程及重难点总结
How about opening an account of Huatai Securities ETF fund? Is it safe
How to package your project and let other users install it through pip
最新可用的二维码生成 api
(ROS_Melodic) 使用Rviz进行Boundingbox可视化
How to calculate the time-consuming code gracefully? (glory Collection Edition)
MySq 数据库约束
测试必会的如何利用fiddler连接手机抓包APP
mysql约束之_外键约束 foreign key
Sharepreference principle + practical analysis
Win10安装QT(在线安装包)闪退(Crash)的问题与解决
Understand JS prototype and prototype chain in one article
第八章 使用时序数据
R language rendering space visualization
Illustration and text demonstrate the movable range of the applet movable view
IO流原理及流的分类
微信小程序云开发常见错误总结.
使用mediapipe和OpenCV实现摄像头实时人脸检测
电商项目如何解决线上优惠券超发(排错+解决方案)(荣耀典藏)


