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 }
  • 相关阅读:
    python基础练习:
    py+selenium切换到新弹出窗口通用方法
    Python 异常处理
    验证码自动化认证部分,可能由于分辨率导致截图不正确
    基于Tesseract的OCR图像识别
    Spark相关知识
    Hive和数据库除了拥有类似的查询语言,再无类似之处;关系型数据库和非关系型数据库的优缺点
    sed替换^A(01),02,03等特殊字符
    Python操作adb命令脚本
    python从放弃到放弃
  • 原文地址:https://www.cnblogs.com/ymj11/p/13809949.html
Copyright © 2011-2022 走看看