zoukankan      html  css  js  c++  java
  • c++的stack容器

    stack是一种容器适配器,专门设计用于在LIFO上下文中操作(后进先出),其中元素仅从容器的一端插入和删除。

    容器适配器,而不是一种容器。

    它是容器适配器是指,只要支持一系列方法的容器(empty, size, back, push_back, pop_back),都能作为stack使用。

    stack 有可能实际上是一个 vector, deque 或 list. 如果没有特殊指明,将使用 deque作为stack的实际容器。

    成员函数

    empty()

    测试栈是否为空,为空返回true,否则返回false。

    bool empty() const;

    size()

    返回栈中元素的个数

    size_type size() const;

    top()

    返回栈顶元素(最后push进来的那个)的引用。

    referenc& top();

    push(val)

    压一个值到栈中,其值将被初始化为 val

    void push(const value_type& val);

    pop()

    将栈顶元素弹出,注意这个函数无返回值,如果需要获取栈顶元素,应先调用top(),再pop()

    swap()

    swap将两个 stack的内容交换。这两个 stack的模板参数 T和 Container必须都相同。

    代码实现:

     1 #include<iostream>
     2 using namespace std;
     3 #include<stack>
     4 #include<algorithm>
     5 
     6 //栈模型
     7 //栈的算法 和 数据类型的分离
     8 
     9 
    10 void main51()
    11 {
    12     stack<int> s;
    13     //入栈
    14     for (int i = 0; i < 10; i++)
    15     {
    16         s.push(i + 1);
    17     }
    18     cout << "栈的大小:" << s.size() << endl;
    19     //出栈
    20     while (!s.empty())
    21     {
    22         int temp = s.top();//获取栈内元素
    23         cout << temp << " ";
    24         s.pop();//弹出栈顶元素
    25     }
    26     cout << endl;
    27 }
    28 
    29 //teacher 结点
    30 class Teacher
    31 {
    32 public:
    33     int age;
    34     char name[32];
    35 public:
    36     void printT()
    37     {
    38         cout << "age: " << age << endl;
    39     }
    40 
    41 
    42 };
    43 
    44 void main52()
    45 {
    46     Teacher t1, t2, t3;
    47     t1.age = 31;
    48     t2.age = 32;
    49     t3.age = 33;
    50 
    51     stack<Teacher> s;
    52     s.push(t1);
    53     s.push(t2);
    54     s.push(t3);
    55     while (!s.empty())
    56     {
    57         Teacher temp = s.top();
    58         temp.printT();
    59         s.pop();
    60     }
    61 }
    62 
    63 
    64 void main53()
    65 {
    66     Teacher t1, t2, t3;
    67     t1.age = 31;
    68     t2.age = 32;
    69     t3.age = 33;
    70 
    71     stack<Teacher *> s;
    72     s.push(&t1);
    73     s.push(&t2);
    74     s.push(&t3);
    75     while (!s.empty())
    76     {
    77         Teacher *temp = s.top();
    78         temp->printT();
    79         s.pop();
    80     }
    81 
    82 }
    83     
    84 int main()
    85 {
    86 
    87     main53();
    88 
    89     system("pause");
    90     return 0;
    91 }
  • 相关阅读:
    一个万能的工具包下载网站
    Keras框架简介
    发现了一个非常棒的pyqt5的例子集
    人脸识别常用数据集大全(12/20更新)
    用 opencv和numpy进行图片和字符串互转,并保存至 json
    机器学习中的范数规则化-L0,L1和L2范式(转载)
    利用face_recognition库裁取人脸
    一招解决C盘空间不足,再也不怕硬盘爆满!
    【LeetCode】394.字符串解码(辅助栈、递归、详细图解)
    程序员那些事儿:女婿程序员
  • 原文地址:https://www.cnblogs.com/ymj11/p/13809949.html
Copyright © 2011-2022 走看看