C++STL----Stack&Queue的使用

文章目录

    • Stack简介
    • Stack的使用
    • Queue简介
    • Queue的使用

Stack简介

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

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

  3. 默认情况下,如果没有为stack指定特定的底层容器,默认情况下使用deque

C++STL----Stack&Queue的使用_第1张图片

Stack的使用

使用默认的适配器定义栈

stack<int> st1;
//没有为stack指定特定的底层容器,默认情况下使用deque。

使用特定的适配器定义栈

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

stack常用的成员函数

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

实列

#include 
#include 
#include 
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简介

  1. 队列是一种容器适配器,专门用于在FIFO上下文(先进先出)中操作,其中从容器一端插入元素,另一端提取元素。
  2. 队列作为容器适配器实现,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从队尾入队列,从队头出队列。
  3. 默认情况下,如果没有为queue实例化指定容器类,则使用标准容器deque。

C++STL----Stack&Queue的使用_第2张图片

Queue的使用

使用默认的适配器定义队列

queue<int> q1;
//没有为queue指定特定的底层容器,默认情况下使用deque

使用特定的适配器定义队列

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

queue中常用的成员函数

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

实列

#include 
#include 
#include 
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;
}

你可能感兴趣的:(C++,c++,开发语言)