zoukankan      html  css  js  c++  java
  • 8、泛型程序设计与c++标准模板库2.5容器适配器

    容器适配器用来扩展7中基本容器的,修改和调整其他类接口的类。他们不提供存放数据的实际数据结构的实现方法,而且容器适配器也不支持迭代器。

    1、标准栈容器

    使用STL中的标准栈为程序员提供了一层附加的保护,下溢和上溢的情况在发生之间就会被捕获。

    标准栈容器是使用适配器与一种基础容器相结合来实现的。使用适配器类,必须要包含他们的头文件,栈是<stack>中声明的。适配器在声明时必须传递参数,指明栈元素的类型及适配器将与那种基础容器向结合。

    容器适配器的参数是某种顺序容器

    例如:

    stack<int,deque<int>> myStack;

    声明了基础容器为deque,元素类型为int的栈对象myStack;

    基础容器提供栈的存储实现,而栈适配器提供特殊的操作功能。基础容器可以用任何顺序容器vector、list或deque实现,默认情况下以容器deque实现。

    例子1:应用标准库中的deque顺序容器生成一个整数栈stack。

    #include<iostream>
    #include<stack>
    using namespace std;
    template<class T>
    void popElements(T &s);
    int main()
    {
     stack<int> intDequeStack;//默认情况下以deque容器作为基础数据结构
     for (int i = 0; i < 10; i++)
      intDequeStack.push(i);//用push函数将整数添加到deque容器stack顶部
     cout << "Popping from intDequeStack:";
     popElements(intDequeStack);//将stack中的元素弹出并输出
     getchar();
     getchar();
     cout << endl;
    }
    template <class T>
    void popElements(T &s)  //定义模板函数
    {
     while (!s.empty())
     {
      cout << s.top() << ' ';//用函数top读取stack顶上的元素并输出
      s.pop();//用函数pop删除顶上的元素
     }
    }

    2.标准队列容器

    标准队列容器也是使用适配器与一种基础容器向结合来实现的,其基础容器通常用列表容器(list)或双端列表容器(deque),默认情况下以deque实现,队列适配器提供特殊的操作功能,可以从基础数据结构的末尾插入元素或在开头删除元素(即入队和出队),例如:

    queue<int,deque<int>> myQueue;

    声明了一个基础容器为deque,元素类型为int的队列对象myQueue。

    队列适配器是在<queue>头文件中声明的。

    例子:应用标准库中的deque顺序容器生成一个整数标准队列Queue

    #include<iostream>
    #include<queue>
    using namespace std;
    template<class T>
    void popElements(T &s);
    int main()
    {
     queue<int> intDueque;//默认情况下以Queue容器作为基础数据结构
     for (int i = 0; i < 10; i++)
      intDueque.push(i);//用push函数将整数添加到deque容器Queue顶部
     cout << "Popping form intDequeQueue:";
     popElements(intDueque);//将Queue中的元素弹出并输出
     getchar();
     getchar();
     cout << endl;
    }
    template<class T>
    void popElements(T& s)//定义模板函数
    {
     while (!s.empty())
     {
      cout << s.front() << ' ';
      s.pop();
     }
    }

  • 相关阅读:
    SMB(Server Message Block) Protocal Research
    IPC$概念及入侵方式研究
    Linux中的pipe(管道)与named pipe(FIFO 命名管道)
    RSA Encrypting/Decrypting、RSA+AES Encrypting/Decrypting
    卷积思想理解、Convolutional Neural Network(CNN)卷积神经网络初探
    IMPLEMENTING A GRU/LSTM RNN WITH PYTHON AND THEANO
    Recurrent Neural Networks(RNN) 循环神经网络初探
    Neural Networks and Deep Learning(神经网络与深度学习)
    基于USB网卡适配器劫持DHCP Server嗅探Windows NTLM Hash密码
    Encryption and decryption、Steganography、Decryption Tools
  • 原文地址:https://www.cnblogs.com/gary-guo/p/6322633.html
Copyright © 2011-2022 走看看