什么是適配器模式?
適配器是一種設(shè)計(jì)模式(設(shè)計(jì)模式是一套被反復(fù)使用的、多數(shù)人知曉的、經(jīng)過(guò)分類編目的、代碼設(shè)計(jì)經(jīng)驗(yàn)的總結(jié)),該種模式是將一個(gè)類的接口轉(zhuǎn)換成客戶希望的另外一個(gè)接口。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-675777.html
STL標(biāo)準(zhǔn)庫(kù)中stack和queue的底層結(jié)構(gòu)
雖然stack和queue中也可以存放元素,但在STL中并沒(méi)有將其劃分在容器的行列,而是將其稱為容器適配器,這是因?yàn)閟tack和隊(duì)列只是對(duì)其他容器的接口進(jìn)行了包裝,STL中stack和queue默認(rèn)使用deque。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-675777.html
stack的模擬實(shí)現(xiàn)
#include <iostream>
#include <deque>
using namespace std;
namespace zha123
{
template<class T, class Container = deque<T>>
class stack
{
public:
void push(const T& val)
{
_con.push_back(val);
}
void pop()
{
_con.pop_back();
}
T& top()
{
return _con.back();
}
size_t size()
{
return _con.size();
}
bool empty()
{
return _con.empty();
}
private:
Container _con;
};
}
queue的模擬實(shí)現(xiàn)
#include <iostream>
#include <deque>
using namespace std;
namespace zha123
{
template<class T, class Container = deque<T>>
class queue
{
public:
void push(const T& x)
{
_con.push_front(x);
}
void pop()
{
_con.pop_back();
}
T& back()
{
return _con.back();
}
const T& back()const
{
return _con.back();
}
T& front()
{
return _con.front();
}
const T& front()const
{
return _con.front();
}
size_t size()const
{
return _con.size();
}
bool empty()const
{
return _con.empty();
}
private:
Container _con;
};
}
到了這里,關(guān)于適配器模式實(shí)現(xiàn)stack和queue的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!