c++---容器适配器

容器适配器

   容器适配器是模板类的一种应用。适配器是什么?适配器就是将外部给予的东西转换成为自己可以使用的东西。可以不用自己实现相关操作。适配器就是用现已有的结构重新封装,得到想要的结构。
   主要举例说一说队列与栈。我们都知道队列的最大特性是先进先出,所以它的相关主要操作就是入队列出队列,对应的就是尾插、头删。所以我们可以用链表来适配队列,因为顺序表的头删很麻烦,需要挪动数据。

栈是后进先出,对应操作为尾插尾删。因为顺序表的尾插尾删很简单,所以我们可以用顺序表来适配。

适配的前提是容器得有所有需要的接口。
适配器的一般格式:
第一个就是普通的存储的数据类型,第二个是适配器的类型,为了让适配器的类型不与队列的数据类型冲突,所以需要让适配器也有模板。我们也可以让适配器有默认的参数,这个默认的参数是一般情况下最适合这个结构的适配器。所以就是下列的结构:

template<class T,template<class>class Container = List>
class Queue
{
    public: 
        void Push();
        void Pop();
        const T& Top();
        bool Empty();
    private:
        Container _con;
};

具体实现如下:
用链表适配实现队列

#include <iostream>
#include "../ListWithTemplate/List.h"
using namespace std;

template<class T,template<class>class Container = List>
class Queue
{
public:
    void Push(const T& x)
    {
        _con.PushBack(x);
    }
    void Pop()
    {
        _con.PopFront();
    }
    const T& Top()
    {
        _con.Top();
    }
    bool Empty()
    {
        _con.Empty();
    }
    void show()
    {
        _con.show();
    }
protected:
    Container<T> _con;
};
int main()
{
    Queue<string,List> q;
    q.Push("This ");
    q.Push("is ");
    q.Push("the ");
    q.Push("statement");
    q.Push("!");
    q.show();
    q.Pop();
    q.show();
    cout<<"队首元素:"<<q.Top()<<endl;
    cout<<q.Empty()<<endl;
    return 0;
}

用顺序表适配实现栈

#include <iostream>
#include <stdio.h>
#include "../Vector/Vector.h"
using namespace std;

template <class T ,template<class>class Container = Vector>
class Stack
{
public:
    void Push(const T& x)
    {
        _con.PushBack(x);
    }
    void Pop()
    {
        _con.PopBack();
    }
    const T& Top()
    {
        _con.Top();
    }
    bool Empty()
    {
       _con.Empty(); 
    }
    void show()
    {
        _con.show();
    }
protected:
    Container<T> _con;
};

int main()
{
    Stack<int,Vector> s;
    s.Push(2);
    s.Push(3);
    s.Push(4);
    s.Push(5);
    s.show();
    cout<<"栈顶元素:"<<s.Top()<<endl;
    s.Pop();
    s.show();
    Stack<int,Vector> s1;
    s1 = s;
    s1.show();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40331034/article/details/80341488