-----------------------------------stack 容器
stack是一种先进后出(first in last out,FILO)的数据结构,他只有一个出口,stack只允许在栈顶新增元素,移除元素,获得元素。
但是除了顶端外,其他地方不允许存取元素,只有栈顶元素才可以被外界使用,也就是说,stack不具备遍历行为,没有迭代器
--------------特性总结:
且不支持随机存取,只能通过top从栈顶获取和删除元素
入栈顺序为:a b c d e
出栈顺序为:e d c b a
--------------stack API
stack 构造函数
stack<T> stkT; stack采用模板类实现,stack对象的默认操作形式
stack (const stack& stk); 拷贝构造函数
stack 赋值操作
stack& operator= (const stack& stk); 重载=操作符
stack 数据存储操作
push(elem); 向栈顶添加元素
pop(); 从栈顶移除第一个元素
top(); 返回栈顶元素
stack 大小操作
empty(); 判断堆栈是否为空
size(); 返回堆栈大小
#include<iostream>
#include<stack>
#include<string>
using namespace std;
void test01 () {
//初始化
stack<int> s1;
stack<int> s2(s1);
//stack操作
s1.push(10);
s1.push(20);
s1.push(30);
s1.push(40);
s1.push(100);
cout << "栈顶元素: " << s1.top() << endl;
//删除栈顶元素
s1.pop();
//打印栈容器数据
while (!s1.empty()) {
cout << s1.top() << " ";
s1.pop();
}
cout << endl;
cout << "size: " << s1.size() << endl;
}
class Person {
public:
Person () {}
Person (string name,int age):name(name),age(age) {}
public:
string name;
int age;
};
//stack 存放对象
void test02 () {
stack<Person> s;
Person p1("zhang",11),p2("li",22),p3("sun",33);
//压入对象
s.push(p1);
s.push(p2);
s.push(p3);
cout << "size: " << s.size() << endl;
//打印对象数据
while (!s.empty()) {
cout << "name: " << s.top().name << " age: " << s.top().age << endl;
s.pop();
}
}
//stack 存放对象指针
void test03 () {
stack<Person*> s;
Person p1("zhang",11),p2("li",22),p3("sun",33);
//压入对象地址
s.push(&p1);
s.push(&p2);
s.push(&p3);
cout << "size: " << s.size() << endl;
//打印对象数据
while (!s.empty()) {
cout << "name: " << s.top()->name << " age: " << s.top()->age << endl;
s.pop();
}
}
int main () {
test01();
test02();
test03();
return 0;
}
var code = "6090004a-6d07-4e91-9dac-bbe2e5fac8db"