stack 只允许在一端进行插入删除,是一个后进先出(LIFO)的结构,可以存储任意类型
queue 只允许在一端进行插入,另一端进行删除,是一个先进先出(FIFO)的结构,可以存储任意类型
模板参数 T 表示存储元素的类型,Container 表示底层使用的容器
一、stack 类和 queue 类的模拟实现
stack 类和 queue 类常用接口模拟实现:
//test.cpp
#include <iostream>
#include <stack>
#include <queue>
#include <vector>
#include <list>
using namespace std;
#include "stack.h"
#include "queue.h"
int main()
{
starrycat::test_stack();
starrycat::test_queue();
return 0;
}
//stack.h
#pragma once
namespace starrycat
{
template<class T, class Container = vector<T>>
class stack
{
public:
void push(const T& x)
{
_con.push_back(x);
}
void pop()
{
_con.pop_back();
}
const T& top() const
{
return _con.back();
}
bool empty() const
{
return _con.empty();
}
size_t size() const
{
return _con.size();
}
private:
Container _con;
};
void test_stack()
{
//stack<int> s;
stack<int, list<int>> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
while (!s.empty())
{
cout << s.top() << " ";
s.pop();
}
cout << endl;
}
}
//queue.h
#pragma once
namespace starrycat
{
template<class T, class Container = list<T>>
class queue
{
public:
void push(const T& x)
{
_con.push_back(x);
}
void pop()
{
_con.pop_front();
}
const T& front() const
{
return _con.front();
}
const T& back() const
{
return _con.back();
}
bool empty() const
{
return _con.empty();
}
size_t size() const
{
return _con.size();
}
private:
Container _con;
};
void test_queue()
{
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
while (!q.empty())
{
cout << q.front() << " ";
q.pop();
}
cout << endl;
}
}