容器适配器(栈容器适配器、队列容器适配器)

我们已有的容器(比如vector、list),这个容器支持的操作很多,比如插入,删除,迭代器访问等等。而我们希望这个容器表现出来的是栈的样子:先进后出,入栈出栈等等,
此时,我们没有必要重新动手写一个新的数据结构,而是把原来的容器重新封装一下,改变它的接口,就能把它当做栈使用了。
c++定义了三种容器适配器,他们让容器提供的接口变成了我们常用的数据结构:栈(先进后出),队列(先进先出),优先级队列。
对于栈来说,主要操作包括:出栈,进栈,栈里元素个数,栈是否为空,栈顶元素;
对于队列来说,主要操作包括:进队,出队,队里元素个数,队是否为空,队头元素。
注:下面代码所用的顺序表和链表相关代码再这篇博客中:
https://blog.csdn.net/sophia__yu/article/details/82993934
接下来将会把栈和队列的容器设配器代码展开:
栈容器适配器

#pragma once

#include"List.h"
#include"Seqlist.h"

template<class T,class Container=Seqlist<T>>  //缺省参数  对于栈来说,适配器默认是顺序表
//Container就是适配器,container是一个模板形参,模板实参传的是什么类型,Container就是什么类型
class Stack
{
public:
	void Push(const T& data) //进栈
	{
		_con.PushBack(data);
	}
	void Pop() //出栈
	{
		_con.PopBack();
	}
	size_t Size()
	{
		return _con.Size();
	}
	bool Empty()
	{
		return _con.Empty();
	}
	T& Top() //返回栈顶元素
	{
		return _con.Top();
	}
private:
	Container _con; 
};

void TestStackCon()
{
	Stack<int, Seqlist<int> >s1;
	s1.Push(1);
	s1.Push(2);
	s1.Push(3);
	cout << s1.Top() << endl;
	s1.Pop();
	cout << s1.Top() << endl;
	cout << s1.Size() << endl;

	Stack<string, Seqlist<string>>s2;
	s2.Push("pick");
	s2.Push("mh");
	cout << s2.Top() << endl;
	s2.Pop();
	cout << s2.Top() << endl;
    
	//Stack<int, Seqlist<char>>s4;
	//s4.Push(4);
	//cout << s4.Top() << endl; //出错

	Stack<int, List<int>>s5;
	s5.Push(10);
	s5.Push(11);
	s5.Push(13);
	s5.Push(14);
	cout << s5.Top() << endl;
	cout << s5.Size() << endl;
}

队列容器适配器

#pragma once
#include"List.h"
#include"Seqlist.h"

//队列容器适配器
//队列先进先出

template<class T, class Container>
class Queue
{
public:
	void Push(const T& data)  //进队
	{
		_con.PushBack(data);
	}
	void Pop()  //出队
	{
		_con.PopFront();
	}
	size_t Size()
	{
		return _con.Size();
	}
	bool Empty()
	{
		return _con.Empty();
	}
	T& Front() //队头元素
	{
		return _con.Front();
	}
private:
	Container _con;
};
void TestQueueCon()
{
	Queue<int, Seqlist<int>> q1;
	q1.Push(10);
	q1.Push(11);
	q1.Push(12);
	q1.Push(13);
	cout << q1.Front() << endl;
	q1.Pop();
	cout << q1.Front() << endl;
	cout << q1.Size() << endl;
}

有了容器适配器,栈和队列就可以用顺序表和链表来做模板参数进行操作。

猜你喜欢

转载自blog.csdn.net/sophia__yu/article/details/83033015