C++——stack容器

目录

1,基本概念

2,stack常用接口


1,基本概念

概念:stack是一种先进后出(first in last out, FILO)的数据结构,它只有一个出口;

栈中只有顶端的元素才可以被外界使用,因此栈不允许有遍历行为。

栈中进入数据称为---入栈 push

栈中弹出数据称为---出栈 pop

生活中与栈类似的东西:弹匣。

2,stack常用接口

构造函数:

stack<T> stk;     //stack采用模板类实现,stack对象的默认构造形式

stack(const stack & stk);   //拷贝构造函数

#include <iostream>
using namespace std;
#include <string>
#include <stack>

void test01()
{
	//默认构造
	stack<int> st1;
	st1.push(10);
	st1.push(20);
	st1.push(30);

	cout << st1.top() << endl;

	//拷贝构造
	stack<int> st2(st1);
}

int main()
{
	test01();
	system("pause");
	return 0;
}

赋值操作:

stack& operator=(const stack &stk);    //重载等号操作符

#include <iostream>
using namespace std;
#include <string>
#include <stack>

void test01()
{
	//默认构造
	stack<int> st1;
	st1.push(10);
	st1.push(20);
	st1.push(30);

	cout << st1.top() << endl;

	stack<int> st2 = st1;
	cout << st2.top() << endl;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

数据存取:

push(elem);  //向栈顶添加元素

pop();    //从栈顶移除第一个元素

top();    //返回栈顶元素

#include <iostream>
using namespace std;
#include <string>
#include <stack>

void test01()
{
	//默认构造
	stack<int> st1;
	st1.push(10);
	st1.push(20);
	st1.push(30);

	cout << st1.top() << endl;

	st1.pop();
	cout << st1.top() << endl;
}

int main()
{
	test01();
	system("pause");
	return 0;
}

大小操作:

empty();     // 判断堆栈是否为空

size();     //返回栈的大小

#include <iostream>
using namespace std;
#include <string>
#include <stack>

void test01()
{
	//默认构造
	stack<int> st1;
	st1.push(10);
	st1.push(20);
	st1.push(30);

	if (st1.empty())
	{
		cout << "栈为空" << endl;
	}
	else
	{
		cout << "栈不为空" << endl;
		cout << "栈的大小为:" << st1.size() << endl;
	}

    
}

int main()
{
	test01();
	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值