C++ stack 的使用

编程入门 行业动态 更新时间:2024-10-20 05:19:55

C++ <a href=https://www.elefans.com/category/jswz/34/1769143.html style=stack 的使用"/>

C++ stack 的使用

目录

1. 无参构造函数

2. void push(const T& x)

3. void pop() 

4. T& top() 

5. bool empty()

6. size_t size()

7. 总结 


1. stack是一种容器适配器,专门用在具有后进先出操作的上下文环境中,其删除只能从容器的一端进行 元素的插入与提取操作。

2. stack是作为容器适配器被实现的,容器适

#include<iostream>
#include<stack>using namespace std;int main()
{stack<int> st;return 0;
}

配器即是对特定类封装作为其底层的容器,并提供一组特定 的成员函数来访问其元素,将特定类作为其底层的,元素特定容器的尾部(即栈顶)被压入和弹出。

3. stack的底层容器可以是任何标准的容器类模板或者一些其他特定的容器类,这些容器类应该支持以下 操作: empty:判空操作 back:获取尾部元素操作 push_back:尾部插入元素操作 pop_back:尾部删除元素操作

4. 标准容器vector、deque、list均符合这些需求,默认情况下,如果没有为stack指定特定的底层容器, 默认情况下使用deque。

上面的内容仅作了解,具体的理解过程会在 stack 的模拟实现部分讲解。

1. 无参构造函数

在 stack 底层,其实使用 STL 的一种容器适配出来的 stack。stack 的无参构造是用得最多的!当然 stack 肯定是有拷贝构造的撒!

#include<iostream>
#include<stack>using namespace std;int main()
{stack<int> st;return 0;
}

2. void push(const T& x)

这个函数可以向栈顶插入一个元素。

#include<iostream>
#include<stack>using namespace std;int main()
{stack<int> st;st.push(1);return 0;
}

3. void pop() 

 这个元素也很简单,就是弹出栈顶的元素!

#include<iostream>
#include<stack>using namespace std;int main()
{stack<int> st;st.push(1);st.pop();return 0;
}

4. T& top() 

返回栈顶的元素。

#include<iostream>
#include<stack>using namespace std;int main()
{stack<int> st;st.push(1);st.push(2);st.push(3);cout << st.top() << endl; //输出:3return 0;
}

5. bool empty()

个函数可以判断一个栈是否为空!为空返回 true,不为空返回 false。

#include<iostream>
#include<stack>using namespace std;int main()
{stack<int> st;st.push(1);st.push(2);st.push(3);cout << st.empty() << endl; //输出:0return 0;
}

6. size_t size()

返回栈中元素的个数。

#include<iostream>
#include<stack>using namespace std;int main()
{stack<int> st;st.push(1);st.push(2);st.push(3);cout << st.size() << endl; //输出:3return 0;
}

7. 总结 

栈是没有迭代器的,他不支持遍历数据。栈只是一种规定了数据插入,删除方式的一种容器。十分简单呢!

更多推荐

C++ stack 的使用

本文发布于:2023-12-03 08:29:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1653221.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:stack

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!