stack容器:
概念:stack是一种先进后出(First in Last out, FILO)的数据结构,它只有一个出口
常用接口:
构造函数:
stack<T> stk; //stack采用模板实现,stack对象默认构造形式
stack(const stack &stk); //拷贝构造函数
赋值操作:
stack & operator=(const stack &stk); //重载=操作符
数据存取:
push(elem); //向栈顶添加元素
pop(); //从栈顶移除第一个元素
top(); //返回栈顶元素
empty(); //判断堆栈是否为空
size(); //返回栈的大小
queue容器:
概念:Queue是一种先进先出(First in First out, FIFO)的数据结构,它有两个出口
常用接口:
构造函数:
queue<T> que; //queue采用模板类实现,queue对象的默认构造形式
queue(const queue &que); //拷贝构造函数
赋值操作:
queue & operator=(const queue &que); //重载=操作符
数据存取:
push(elem); //往队尾添加元素
pop(); //从对头移除第一个元素
back(); //返回最后一个元素
front(); //返回第一个元素
empty(); //判断队列是否为空
size(); //返回队列大小
#include <iostream>
using namespace std;
#include <stack>
#include <queue>
satckコンテナ:
void test01()
{
//特点:符合先进后出数据结构
stack<int> s;
//入栈
s.push(10);
s.push(20);
s.push(30);
//判断是否为空,查看栈顶,出栈
if (!s.empty()){
cout << "栈顶数据为: " << s.top() <<endl;
cout << "size = " << s.size() << endl;
s.pop();
cout << "栈顶数据为: " << s.top() <<endl;
cout << "size = " << s.size() << endl;
}else{
cout << "该栈为空" << endl;
}
}
キューコンテナ:
class Person
{
public:
Person(string name, int age)
{
this -> m_Name = name;
this -> m_Age = age;
}
string m_Name;
int m_Age;
};
test02()
{
queue<Person> q;
Person p1("唐僧", 28);
Person p2("孙悟空", 1000);
Person p3("猪悟能", 999);
Person p4("沙悟净", 888);
Person p5("白龙马", 233);
q.push(p1);
q.push(p2);
q.push(p3);
q.push(p4);
q.push(p5);
cout << "size = " << q.size() << endl;
while (!q.empty()){
//查看队头
cout << "队头元素 姓名:" << q.front().m_Name << " 年龄: " << q.front().m_Age << endl;
//查看队尾
cout << "队尾元素 姓名:" << q.back().m_Name << " 年龄: " << q.back().m_Age << endl;
//出队
q.pop();
}
cout << "size = " << q.size() << endl;
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
*ダークホースプログラマーc ++コース学習演習