C++STL(四) stack、queue容器

32 篇文章 0 订阅

stack容器基本概念

stack是一种先进后出(First In Last Out,FILO)的数据结构,它只有一个出口,形式如图所示。stack容器允许新增元素,移除元素,取得栈顶元素,但是除了最顶端外,没有任何其他方法可以存取stack的其他元素。换言之,stack不允许有遍历行为。

有元素推入栈的操作称为:push,将元素推出stack的操作称为pop.

stack常用API

 stack构造函数

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

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

stack赋值操作

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

stack数据存取操作

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

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

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

stack大小操作

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

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

Queue容器基本概念

Queue是一种先进先出(First In First Out,FIFO)的数据结构,它有两个出口,queue容器允许从一端新增元素,从另一端移除元素。

queue常用API

queue构造函数

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

queue(const queue &que);//拷贝构造函数

queue存取、插入和删除操作

push(elem);//往队尾添加元素

pop();//从队头移除第一个元素

back();//返回最后一个元素

front();//返回第一个元素

queue赋值操作

queue&operator=(const queue &que);//重载等号操作符

queue大小操作

empty();//判断队列是否为空

size();//返回队列的大小

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

//push
//pop
//top
//empty
//size

void test01() {
	stack<int> s1;
	s1.push(1);
	s1.push(2);
	s1.push(3);
	s1.push(4);

	cout << s1.size() << endl;
	for (int i = 0;!s1.empty(); i++) {
		cout << s1.top() << endl;
		s1.pop();
	}
}

//push
//pop
//front
//back
//empty
//size

void test02() {
	queue<int> q1;
	q1.push(1);
	q1.push(2);
	q1.push(3);
	q1.push(4);

	cout << q1.back() << endl;

	for (int i = 0; q1.size()!=0; ++i) {
		cout << i << ".front=" << q1.front() << endl;
		q1.pop();
	}
}

int main() {
	test01();
	cout << "---------------" << endl;
	test02();
	system("pause");
	return EXIT_SUCCESS;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值