Stack
简介
stack 是堆栈容器, 是一种“先进后出” 的容器。
stack 是简单地装饰 deque 容器而成为另外的一种容器。
stack 是堆栈容器, 是一种“先进后出” 的容器。
stack 是简单地装饰 deque 容器而成为另外的一种容器。
#include <stack>
stack
对象的默认构造
stack 采用模板类实现, stack 对象的默认构造形式: stack <T> s;
stack <int> s; // 一个存放 int 的 stack 容器。
stack <float> s; // 一个存放 float 的 stack 容器。
stack <string> s; // 一个存放 string 的 stack 容器。 // 尖括号内还可以设置指针类型或自定义类型。
stack 的 push() 与 pop() 方法
stack.push(elem); // 往栈头添加元素
stack.pop(); // 从栈头移除第一个元素
stack 对象的拷贝构造与赋值
stack.size(); //
返回堆栈的大小
stack 采用模板类实现, stack 对象的默认构造形式: stack <T> s;
stack <int> s; // 一个存放 int 的 stack 容器。
stack <float> s; // 一个存放 float 的 stack 容器。
stack <string> s; // 一个存放 string 的 stack 容器。 // 尖括号内还可以设置指针类型或自定义类型。
stack 的 push() 与 pop() 方法
stack.push(elem); // 往栈头添加元素
stack.pop(); // 从栈头移除第一个元素
stack 对象的拷贝构造与赋值
stack(const stack &stk); | //拷贝构造函数 |
stack& operator=(const stack &stk); | //重载等号操作符 |
stack<int> stkIntA; stkIntA.push(1); stkIntA.push(3); stkIntA.push(5); stkIntA.push(7); stkIntA.push(9); stack<int> stkIntB(stkIntA); |
//拷贝构造 |
stack<int> stkIntC; stkIntC = stkIntA; |
//赋值 |
/////////////////////////////////////应用案例//////////////////////////////////////
#include"iostream" #include"stack" using namespace std; class Student { public: int age; char name[32]; void print() { cout << "age: " << age << endl; } }; int main01() { stack<int> s; s.push(1);//入栈 s.push(2); s.push(3); while(!s.empty()) { int tem = s.top();//获取栈顶元素; cout << tem <<endl; s.pop();//出栈 } cout << endl; return 0; } int main02() { stack<Student>s; Student t1, t2, t3; t1.age = 20; t2.age = 21; t3.age = 22; s.push(t1); s.push(t2); s.push(t3); while (!s.empty()) { Student t = s.top(); t.print(); s.pop(); } return 0; } int main03() { stack<Student*>s1; Student t1, t2, t3; t1.age = 20; t2.age = 21; t3.age = 22; s1.push(&t1); s1.push(&t2); s1.push(&t3); while (!s1.empty()) { Student* t1 = s1.top(); t1->print(); s1.pop(); } return 0; } int main() { main01(); main02(); main03(); system("pause"); return 0; }
Queue 简介
queue 是队列容器, 是一种“先进先出” 的容器。
queue 是简单地装饰 deque 容器而成为另外的一种容器。
#include <queue>
queue 对象的默认构造
queue 采用模板类实现, queue 对象的默认构造形式: queue<T> q;
queue 的 push()与 pop()方法
queue.push(elem); //往队尾添加元素
queue.pop(); //从队头移除第一个元素
queue 对象的拷贝构造与赋值
queue(const queue &que); //拷贝构造函数
queue& operator=(const queue &que); //重载等号操作符
queue 的数据存取
queue.back(); //返回最后一个元素
queue.front(); //返回第一个元素
queue.back(); //返回最后一个元素
queue.front(); //返回第一个元素
queue 的大小
queue.empty(); //判断队列是否为空
queue.size(); //返回队列的大小
例程与堆栈相同;将stack改为queue即可。