stack容器
基本概念
概念
stack是一种先进后出(First In Last Out,FILO)的数据结构,它只有一个出口
栈中只有顶端的元素才可以被外界使用,因此栈不允许有遍历行为
栈中进入数据称为–入栈push
栈中弹出数据称为–出栈pop
常用接口
功能描述:栈容器常用的对外接口
构造函数:
1 2
| stack<T> stk; stack(const stack &stk);
|
赋值操作:
1
| stack& operator=(const stack &stk);
|
数据存取:
1 2 3
| push(elem); pop(); top();
|
大小操作:
总结
- 入栈–push
- 出栈–pop
- 返回栈顶–top
- 判断栈是否为空–empty
- 返回栈大小–size
Demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #include<iostream> #include<stack> using namespace std;
void test01() { stack<int>s; s.push(10); s.push(20); s.push(30); s.push(40); while (!s.empty()) { cout << "栈顶元素为:" << s.top() << endl; s.pop(); } cout << "栈的大小:" << s.size() << endl; } int main() { test01(); system("pause"); return 0; }
|
运行结果
1 2 3 4 5
| 栈顶元素为:40 栈顶元素为:30 栈顶元素为:20 栈顶元素为:10 栈的大小:0
|
queue容器
基本概念
概念
Queue是一种先进先出(First In First Out,FIFO)的数据结构,它有两个出口
队列容器允许从一段新增元素,从另一端移除元素
队列中只有队头和队尾才可以被外界使用,因此队列不允许有遍历行为
队列中进数据称为—入队push
队列中出数据称为—出队pop
常用接口
功能描述:栈容器常用的对外接口
构造函数:
1 2
| queue<T> que; queue(const queue &que);
|
赋值操作:
1
| queue& operator=(const queue &que);
|
数据存取:
1 2 3 4
| push(elem); pop(); back(); front();
|
大小操作:
总结
- 入队—push
- 出队—pop
- 返回队头元素—front
- 返回队尾元素—back
- 判断队是否为空—empty
- 返回队列大小—size
Demo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #include<iostream> #include<queue> using namespace std;
class Person { public: Person(string name, int age) { this->m_Name = name; this->m_Age = age; } string m_Name; int m_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().m_Name << "年龄:" << q.front().m_Age << endl; cout << "队尾元素---姓名:" << q.back().m_Name << "年龄:" << q.front().m_Age << endl; q.pop(); } cout << "队列大小为:" << q.size() << endl; } int main() { test01(); system("pause"); return 0; }
|
运行结果
1 2 3 4 5 6 7 8 9 10
| 队列大小为:4 队头元素---姓名:唐僧年龄:30 队尾元素---姓名:沙僧年龄:30 队头元素---姓名:孙悟空年龄:1000 队尾元素---姓名:沙僧年龄:1000 队头元素---姓名:猪八戒年龄:900 队尾元素---姓名:沙僧年龄:900 队头元素---姓名:沙僧年龄:800 队尾元素---姓名:沙僧年龄:800 队列大小为:0
|