C++ STL标准模板库(stack)

//stack的使用
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<stack>
using namespace std;

/*
引用头文件   #include<stack>

stack类本身是一个类模板

stack(堆栈) 是一个容器类的改编,为程序员提供了堆栈的全部功能,—
—也就是说实现了一个先进后出(FILO)的数据结构。
1.empty() 堆栈为空则返回真
2.pop() 移除栈顶元素
3.push() 在栈顶增加元素
4.size() 返回栈中元素数目
5.top() 返回栈顶元素

*/

class Student{
public:
    int age;
    char name[30];
};

void ProtectA(){
    //跟vector不同,不需要初始化初始元素个数
    stack<Student *> ss1;
    Student s1, s2, s3;
    s1.age = 12;
    strcpy(s1.name, "小米");
    s2.age = 14;
    strcpy(s2.name, "小红");
    s3.age = 16;
    strcpy(s3.name, "小刚");
    //添加元素
    ss1.push(&s1);
    ss1.push(&s2);
    ss1.push(&s3);
    //弹出栈顶元素
    while (!ss1.empty()){
        //获取栈顶元素
        Student * temp = ss1.top();
        cout << "学生姓名:" << temp->name << ";学生年龄是:" << temp->age << endl;
        //弹出栈顶元素
        ss1.pop();
    }
}

void main(){
    ProtectA();
    system("pause");
}
原文地址:https://www.cnblogs.com/zhanggaofeng/p/5666472.html