C++ stack 的使用

目录

[1. 无参构造函数](#1. 无参构造函数)

[2. void push(const T& x)](#2. void push(const T& x))

[3. void pop()](#3. void pop())

[4. T& top()](#4. T& top())

[5. bool empty()](#5. bool empty())

[6. size_t size()](#6. size_t size())

[7. 总结](#7. 总结)


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

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

cpp 复制代码
#include<iostream>
#include<stack>

using namespace std;

int main()
{
	stack<int> st;
	return 0;
}

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

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

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

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

1. 无参构造函数

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

cpp 复制代码
#include<iostream>
#include<stack>

using namespace std;

int main()
{
	stack<int> st;
	return 0;
}

2. void push(const T& x)

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

cpp 复制代码
#include<iostream>
#include<stack>

using namespace std;

int main()
{
	stack<int> st;
	st.push(1);
	return 0;
}

3. void pop()

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

cpp 复制代码
#include<iostream>
#include<stack>

using namespace std;

int main()
{
	stack<int> st;
	st.push(1);
	st.pop();
	return 0;
}

4. T& top()

返回栈顶的元素。

cpp 复制代码
#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; //输出:3
	return 0;
}

5. bool empty()

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

cpp 复制代码
#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; //输出:0
	return 0;
}

6. size_t size()

返回栈中元素的个数。

cpp 复制代码
#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; //输出:3
	return 0;
}

7. 总结

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

相关推荐
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20215 天前
信号量和信号
linux·c++
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc