手动实现标准库中的栈和队列
#include <iostream>
#include<exception>
using namespace std;
template<typename T>
class my_Stack
{
private:
T *ptr;
int len; //当前个数
int max=15;//容器最大容量
private:
void cap(){//二倍扩容
max=max*2;
T *qtr=new T[max];
for(int i=0;i<len;i++){
qtr[i]=ptr[i];
}
delete [] ptr;
ptr=qtr;
}
public:
my_Stack():len(0) {
ptr=new T [max];
cout<<"无参构造"<<endl;
}
~my_Stack(){
delete []ptr;
cout<<"析构函数"<<endl;
}
my_Stack &operator=(my_Stack &other){//拷贝赋值
if(this!=&other){
delete []ptr;
this->len=other.len;
this->max=other.max;
this->ptr=new int[this->max];
for(int i=0;i<len;i++){
ptr[i]=other.ptr[i];
}
}
return *this;
}
//返回栈内首元素
T &my_top(){
if(my_empty()){
throw out_of_range("Stack is empty");
}
return ptr[0];
}
//判断栈内是否为空
bool my_empty(){
return len==0;
}
//返回容纳个数
int my_size(){
return len;
}
bool my_full(){
if(len==max){
return true;
}
return false;
}
//入栈
bool my_push(T key){
if(my_full()){
cap();
}
ptr[len]=key;
len++;
return true;
}
// 出栈
bool my_pop() {
if (my_empty()) {
return false;
}
len--;
return true;
}
void show(){
cout<<len<<endl;
for(int i=0;i<len;i++){
cout<<ptr[i]<<" ";
}
cout<<endl;
}
};
int main()
{
my_Stack<string> s1;
cout<<"****************"<<endl;
return 0;
}
#include <iostream>
#include<exception>
using namespace std;
template<typename T>
class my_queue
{
private:
T *ptr;
int len; //当前个数
int max=15;//容器最大容量
private:
void cap(){//二倍扩容
int *qtr=new int[max*2];
for(int i=0;i<len;i++){
qtr[i]=ptr[i];
}
delete [] ptr;
ptr=qtr;
}
public:
my_queue():len(0) {
ptr=new T [max];
cout<<"无参构造"<<endl;
}
~my_queue(){
delete []ptr;
cout<<"析构函数"<<endl;
}
my_queue &operator=(my_queue &other){//拷贝赋值
if(this!=&other){
delete []ptr;
this->len=other.len;
this->max=other.max;
this->ptr=new int[this->max];
for(int i=0;i<len;i++){
ptr[i]=other.ptr[i];
}
}
return *this;
}
//返回队内首元素
T &my_front(){
if(my_empty()){
throw out_of_range("this queue is empty");
}
return ptr[0];
}
//返回对内尾元素
int &my_back(){
return ptr[len-1];
}
//判断队内是否为空
bool my_empty(){
return len==0;
}
//返回容纳个数
int my_size(){
return len;
}
bool my_full(){
if(len==max){
return true;
}
return false;
}
//入队
bool my_push(int key){
if(my_full()){
cap();
}
ptr[len]=key;
len++;
return true;
}
//出队
bool my_pop(){
if(len==0){
return false;
}
for(int i=0;i<len;i++){
ptr[i]=ptr[i+1];
}
len--;
return true;
}
};
int main()
{
my_queue<int> q1;
cout<<q1.my_size()<<endl;
return 0;
}
思维导图: