• c++STL(栈、队列)


    栈stack

    -先入后出FILO

    栈可以理解为一个坑,先掉坑里的被压在下面,等上面的走了才能出来

    头文件                <stack>

    入栈                 push(某东西);

    栈顶元素出栈             pop();

    是否为空               empty();  空返回1  非空返回0

    大小                 size();  返回元素个数

    查看栈顶(只是查看,下面的也一样)  top();  返回栈顶元素  //如果栈是空的再看栈顶元素就要出事咯

    队列

    -先入先出FIFO

     头文件      <queue>

    入队       push(某东西);

    出队       pop();

    查看队首     front();  返回队首元素

    查看队尾     back();  返回队尾元素

    是否为空     empty();  空返回1  非空返回0

    大小       size();  返回元素个数

    e.g.

     1 #include<iostream>
     2 #include<stdio.h>
     3 #include<stack>
     4 #include<queue>
     5 using namespace std;
     6 struct node
     7 {
     8     int a, b;
     9     /*bool operator <(const node&x)const
    10     {
    11         if (a == x.a)return b < x.b;
    12         return a < x.a;
    13     }*/
    14 };
    15 int main()
    16 {
    17     stack<int>sa;    //声明一个stack  <栈中存储的数据类型>  变量名;
    18     stack<node>sb;    //也可以放结构体
    19     queue<int>q;
    20     for (int i = 0; i < 10; i++)
    21     {
    22         sa.push(i);
    23         q.push(i);
    24     }
    25     printf("size of the stack sa is %d
    ", sa.size());
    26     printf("size of the queue q is %d
    ", q.size());
    27     cout << "elements in sa are:
    ";
    28     while (!sa.empty())        //若当前容器非空,则输出第一个,再将第一个删去
    29     {
    30         cout << sa.top()<<endl;
    31         sa.pop();
    32     }    
    33     cout << "elements in q are:
    ";
    34     while (!q.empty())
    35     {
    36         cout << q.front()<<endl;
    37         q.pop();
    38     }
    39 }

    输出结果:

    size of the stack sa is 10
    size of the queue q is 10
    elements in sa are:
    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    elements in q are:
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

  • 相关阅读:
    在Window上Vim包的选择
    如何在apache官网下载将将jar包
    hdu1870
    hdu1710(Binary Tree Traversals)
    poj 3252 Round Numbers 【推导·排列组合】
    3905
    Find them, Catch them
    Argus
    Team Queue
    Terrible Sets
  • 原文地址:https://www.cnblogs.com/jinmingyi/p/6798041.html
Copyright © 2020-2023  润新知