stack常用接口
s.push()
s.empty()
s.top()
s.pop()
s.size()
#include<bits/stdc++.h>
using namespace std;
void test01()
{
//特点:符合先进后出数据结构
stack<int>s;
//入栈
s.push(10);
s.push(20);
s.push(30);
s.push(40);
cout << "栈的大小:" << s.size() << endl;
//只要栈不为空,查看栈顶,并且执行出栈操作
while (!s.empty())
{
//查看栈顶元素
cout << "栈顶元素为:" << s.top() << endl;
//出栈
s.pop();
}
cout << "栈的大小:" << s.size() << endl;
}
int main()
{
test01();
return 0;
}
queue常用接口
q.push()
q.size()
q.empty()
q.front()
q.back()
q.pop()
#include<bits/stdc++.h>
using namespace std;
class Person
{
public:
string name;
int age;
Person(string name, int age)
{
this->name = name;
this->age = age;
}
};
void test01()
{
//创建队列
queue<Person>q;
//准备数据
Person p1("唐僧", 30);
Person p2("孙悟空", 1000);
Person p3("猪八戒", 900);
Person p4("沙僧", 800);
//入队
q.push(p1);
q.push(p2);
q.push(p3);
q.push(p4);
//判断只要队列不为空,查看对头,查看队尾,出队
cout << "队列大小为:" << q.size() << endl;
while (!q.empty())
{
//查看队头
cout << "队头元素--姓名:" << q.front().name << "年龄:" << q.front().age << endl;
//查看队尾
cout << "队尾元素--姓名:" << q.back().name << "年龄:" << q.back().age << endl;
//出队
q.pop();
}
cout << "队列大小为:" << q.size() << endl;
}
int main()
{
test01();
return 0;
}