目录
一、stack介绍
使用方法
函数说明 | 接口说明 |
stack() | 构造空的栈 |
empty() | 检测stack是否为空 |
size() | 返回stack中元素的个数 |
top() | 返回栈顶元素的引用 |
push() | 将元素val压入stack中 |
pop() | 将stack中尾部的元素弹出 |
void testStack()
{
stack<int> st;
//入栈
st.push(1);
st.push(2);
st.push(3);
st.push(4);
if (st.empty())
{
cout << "判空:true" << endl;
}
else
cout << "判空:false" << endl;
cout << "st容量:" << st.size() << endl;
cout << "栈顶元素值:" << st.top() << endl;
//出栈
cout << "出栈元素:";
while (!st.empty())
{
cout << st.top() << " ";
st.pop();
}
}
int main()
{
testStack();
return 0;
}
二、queue介绍
queue的使用
函数声明 | 接口说明 |
queue() | 构造空的队列 |
empty() | 检测队列是否为空,是返回true,否则返回false |
size() | 返回队列中有效元素的个数 |
front() | 返回队头元素的引用 |
back() | 返回队尾元素的引用 |
push() | 在队尾将元素val入队列 |
pop() | 将队头元素出队列 |
void testQueue()
{
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
//判空
if (q.empty())
{
cout << "判空:true" << endl;
}
else
cout << "判空:false" << endl;
cout << "队头元素:" << q.front() << endl;
cout << "队尾元素:" << q.back() << endl;
cout << "队列的大小:" << q.size() << endl;
cout << "出队列";
while (!q.empty())
{
cout << q.front() << " ";
q.pop();
}
}
int main()
{
testQueue();
return 0;
}
三、priority_queeue 优先级队列介绍
函数声明 | 接口说明 |
priority_queue()/priority_queue(first, last) | 构造一个空的优先级队列 |
empty( ) | 检测优先级队列是否为空,是返回true,否则返回 false |
top( ) | 返回优先级队列中最大(最小元素),即堆顶元素 |
push(x) | 在优先级队列中插入元素x |
pop() | 删除优先级队列中最大(最小)元素,即堆顶元素 |
void TestPriorityQueue()
{
// 默认情况下,创建的是大堆,其底层按照小于号比较
vector<int> v{ 3,2,7,6,0,4,1,9,8,5 };
priority_queue<int> q1;
for (auto& e : v)
q1.push(e);
//cout << q1.top() << endl;
cout << "q1:";
while (!q1.empty())
{
cout << q1.top() << " ";
q1.pop();
}
cout << endl<<"q2:";
// 如果要创建小堆,将第三个模板参数换成greater比较方式
priority_queue<int, vector<int>, greater<int>> q2(v.begin(), v.end());
while (!q2.empty())
{
cout << q2.top() << " ";
q2.pop();
}
}
int main()
{
TestPriorityQueue();
return 0;
}