c++之stl_queue、stl_stack
一、简介
c++里queue和stack严格来讲,不应叫做容器,应该叫做容器适配器(container adaptor),它们没有任何实现,使用其他容器作为底层容器,直接调用底层容器的实现。我们直接使用deque容器作为底层容器。deque的解析请戳这里。
1. queue
先进先出(first in first out)。
#if !defined(_M_QUEUE)
#define _M_QUEUE
#include "m_deque.h"
namespace learnCpp
{
template <typename T>
class m_queue
{
public:
typedef T &ref;
typedef T valueType;
protected:
m_deque<T> container;
public:
m_queue()
: container()
{
}
size_t max_size()
{
return container.max_size();
}
bool empty() const
{
return container.empty();
}
void push(const valueType &val)
{
container.push_back(val);
}
void pop()
{
container.pop_front();
}
ref front()
{
return container.front();
}
ref back()
{
return container.back();
}
};
} // namespace learnCpp
#endif // _M_QUEUE
2. stack
先进后出(first in last out)。
#if !defined(_M_STACK)
#define _M_STACK
#include "m_deque.h"
namespace learnCpp
{
template <typename T>
class m_stack
{
public:
typedef T &ref;
protected:
m_deque<T> container;
public:
m_stack() : container()
{
}
size_t max_size()
{
return container.max_size();
}
bool empty() const
{
return container.empty();
}
void push(const T &val)
{
container.push_front(val);
}
void pop()
{
container.pop_front();
}
ref top()
{
return container.front();
}
};
} // namespace learnCpp
#endif // _M_STACK
二、测试
1. 测试代码
#include "m_queue.h"
#include "m_stack.h"
#include <iostream>
using namespace std;
using namespace learnCpp;
void queueTest()
{
m_queue<string> q;
for (size_t i = 50; i > 0; i--)
{
q.push(to_string(i));
}
int len = q.max_size();
cout << "size : " << len << endl;
for (size_t i = 0; i < len; i++)
{
cout << q.front() << " ";
q.pop();
}
}
void stackTest()
{
m_stack<string> s;
for (size_t i = 0; i < 50; i++)
{
s.push(to_string(i));
}
int len = s.max_size();
cout << "size : " << len << endl;
for (size_t i = 0; i < 30; i++)
{
cout << s.top() << " ";
s.pop();
}
for (size_t i = 0; i < 20; i++)
{
s.push(to_string(i));
}
int len1 = s.max_size();
cout << endl
<< "size : " << len1 << endl;
for (size_t i = 0; i < len1; i++)
{
cout << s.top() << " ";
s.pop();
}
}
int main(int argc, char const *argv[])
{
cout<< "queueTest:" << endl;
queueTest();
cout << endl
<< endl
<< "stackTest:" << endl;
stackTest();
return 0;
}