文章目录

Stack
Stack是一种容器,是基本的数据结构之一,特点是先进后出。
定义方式
方式一:普通定义方式
cpp
stack<int> st1;
方式二:
cpp
stack<int,vector<int>> st2;
stack<int,list<int>> st3
注意: 如果没有为stack指定特定的底层容器,默认情况下使用deque。
使用方式
stack当中常用的成员函数如下:
成员函数 | 功能 |
---|---|
empty | 判断栈是否为空 |
size | 获取栈有效元素个数 |
top | 获取栈顶元素 |
push | 元素入栈 |
pop | 元素出栈 |
swap | 交换两个栈的数据 |
cpp
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
队列是一种容器适配器,专门用在具有先进先出操作的上下文环境中,其只能从容器的一端插入元素,另一端提取元素。
定义方式
cpp
queue的定义方式
方式一: 使用默认的适配器定义队列。
queue<int> q1;
方式二: 使用特定的适配器定义队列。
queue<int, vector<int>> q2;
queue<int, list<int>> q3;
使用方式
成员函数 | 功能 |
---|---|
empty | 判断队列是否为空 |
size | 获取队列有效元素个数 |
front | 获取队头元素 |
back | 获取队尾元素 |
push | 元素入队列 |
pop | 元素出队列 |
swap | 交换两个队列的数据 |
cpp
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;