目录
💕 1.适配器Container
💕2.真实的底层实现
💕3.测试用例
💕4.完结
一个人的坚持到底有多难
声明:需先了解vector,list,stack的使用
💕 1.适配器Container
在实现栈的底层实现时,我们需要用到一个新的东西,Container,也叫做适配器,它其实是一种模板参数,具体使用如下->:
#pragma once #include<iostream> #include<vector> #include<list> using namespace std; namespace yzq {//适配器Container —— 转换(用别的STL进行转换)template<class T,class Container = vector<T>>class Stack{private:Container con;}; }
Container这个参数的作用是让用户可以指定容器适配器所使用的底层容器,从而灵活地根据具体需求选择不同的底层数据结构。
这里就默认Container为顺序表类型的数据结构
我们的成员变量con,默认情况下就是顺序表类型,因此,我们如果想实现栈的尾插,我们就可以这样写->:
#pragma once #include<iostream> #include<vector> #include<list> using namespace std; namespace yzq {//适配器Container —— 转换(用别的STL进行转换)template<class T,class Container = vector<T>>class Stack{void push(const T& x){con.push_back(x);}private:Container con;}; }
以此为戒,我们可以实现栈的各种功能
#pragma once #include<iostream> #include<vector> #include<list> #include <stack> #include<string> using namespace std; namespace yzq {//适配器Container —— 转换(用别的STL进行转换)template<class T,class Container = vector<T>>class Stack{public://尾插(入栈)void push(const T& x){con.push_back(x);}//尾删(出栈)void pop(){con.pop_back();}const T& top(){return con.back();}bool empty(){return con.empty();}size_t size(){return con.size();}private:Container con;}; }
这样一个栈的底层功能就实现了
💕2.真实的底层实现
但是栈真实的底层实现,它的模板并不是使用vector作为默认值的,它使用的是一个双端队列 deque , 双端队列可以理解为一种顺序表和链表的结合体,它结合了向量(
vector
)和列表(list
)的部分优点,允许在容器的两端高效地插入和删除元素。了解即可,不必钻研
真实的底层实现->:
#pragma once #include<iostream> #include<vector> #include<list> #include <stack> #include<string> using namespace std; namespace yzq {//适配器Container —— 转换(用别的STL进行转换)template<class T,class Container = deque<T>>class Stack{public://尾插(入栈)void push(const T& x){con.push_back(x);}//尾删(出栈)void pop(){con.pop_back();}const T& top(){return con.back();}bool empty(){return con.empty();}size_t size(){return con.size();}private:Container con;}; }
💕3.测试用例
#define _CRT_SECURE_NO_WARNINGS #include"Stack.h" int main() {yzq::Stack<int,vector<int>> s1;//这代表,这个栈的数据是int类型的,底层使用的是vector的函数功能s1.push(2);s1.push(3);cout << s1.size()<< endl;yzq::Stack<string,list<string>> s2;//这代表,这个栈的数据是string类型的,底层使用的是list的函数功能s2.push("hello");s2.push("world");cout << s2.size() << endl; }