STL详解(七)—— stack和queue的介绍及使用
  TEZNKK3IfmPf 28天前 24 0
 

stack

stack是一种容器适配器,专门用在具有后进先出操作的上下文环境中,其只能从容器的一端进行元素的插入与提取操作。
STL详解(七)—— stack和queue的介绍及使用

stack的定义方式

方式一: 使用默认的适配器定义栈。

stack<int> st1;

方式二: 使用特定的适配器定义栈。

stack<int, vector<int>> st2;
stack<int, list<int>> st3;

注意: 如果没有为stack指定特定的底层容器,默认情况下使用deque。

stack的使用

stack当中常用的成员函数如下:

成员函数 功能
empty 判断栈是否为空
size 获取栈中有效元素个数
top 获取栈顶元素
push 元素入栈
pop 元素出栈
swap 交换两个栈中的数据

示例:

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

int main()
{
     
       
	stack<int, vector<int>> st;
	st.push(1);
	st.push(2);
	st.push(3);
	st.push(4);
	cout << st.size() << endl; //4
	while (!st.empty())
	{
     
       
		cout << st.top() << " ";
		st.pop();
	}
	cout << endl; //4 3 2 1
	return 0;
}

queue

队列是一种容器适配器,专门用在具有先进先出操作的上下文环境中,其只能从容器的一端插入元素,另一端提取元素。
STL详解(七)—— stack和queue的介绍及使用

queue的定义方式

方式一: 使用默认的适配器定义队列。

queue<int> q1;

方式二: 使用特定的适配器定义队列。

queue<int, vector<int>> q2;
queue<int, list<int>> q3;

注意: 如果没有为queue指定特定的底层容器,默认情况下使用deque。

queue的使用

queue当中常用的成员函数如下:

成员函数 功能
empty 判断队列是否为空
size 获取队列中有效元素个数
front 获取队头元素
back 获取队尾元素
push 队尾入队列
pop 队头出队列
swap 交换两个队列中的数据

示例:

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

int main()
{
     
       
	queue<int, list<int>> q;
	q.push(1);
	q.push(2);
	q.push(3);
	q.push(4);
	cout << q.size() << endl; //4
	while (!q.empty())
	{
     
       
		cout << q.front() << " ";
		q.pop();
	}
	cout << endl; //1 2 3 4
	return 0;
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 28天前 0

暂无评论

推荐阅读
TEZNKK3IfmPf