温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

c++模板实现栈

发布时间:2020-06-16 04:26:36 来源:网络 阅读:462 作者:马尾和披肩 栏目:编程语言
栈的管理可以用运链表,当然啦也可以用运数组,相比链表而数组管理起来更加方便,为什么呢???请睁大眼睛看下边博主大人的总结 数组管理栈的优点: (1)插入删除方便,数组直接将++_top或者--_top即可,而链表还要删除节点置空指针,麻烦死啦; (2)效率高呀,数组一次能够new T [_capacity]省事,而链表边用边new; (3)其实这里还牵扯到一个cpu的高速缓存利用率

c++模板实现栈

static and queue.h

#pragma  once

#include<iostream>

using namespace std;

template<class T>

class stack

{

public:


    stack()

:_a(0)

,_top(0)

,_capacity(0)

{}

   //刚开始写这个函数的时候很傻比,哎,下次一定铭记

stack(const stack <T>& s)

:_a(new T[s._capacity])

    ,_top(s._top)

,_capacity(s._capacity)

{

int i=0;

for(i=0;i<s._top;i++)

{

_a[i]=s._a[i];

}


}

stack<T>& operator=(const stack<T>& s)

{

if(this!=&s)

{

delete [] _a;

_a=new T [s._capacity*sizeof(T)];

int i=0;

for(i=0;i<_top;i++)

{

a[i]=s._a[i];

}

_top=s._top;

_capacity=s._capacity;


}

return *this;

}

~stack()

{

if(_a!=NULL)

{

delete [] _a;

_a=NULL;

}

}

//栈扩容函数

void _checkcapacity()

{

//不能用realloc开辟因为它不会调用构造和析构函数

              if(_top==_capacity)

{

_capacity=_capacity*2+3;

               

T* tmp=new T [_capacity];

int i=0;

for(i=0;i<_top;i++)

{

tmp[i]=_a[i];

}

delete [] _a;

_a=tmp;

}

}

void push(const T& x);

void pop();

T& top();

bool empty();

size_t size();

void print();

protected:

T * _a;

size_t _top;

size_t _capacity;

};

static and queue.cpp #define _CRT_SECURE_NO_WARNINGS 1 #include"stack and queue.h" #include<assert.h> using namespace std; template<class T> void stack<T>::print() {	while(!empty())	{	cout<<_top<<" ";	pop();	}	cout<<"over"<<endl;; } template<class T> void stack<T>::push(const T& x) {    _checkcapacity();    _a[_top++]=x; } template<class T> void stack<T>::pop() {	if(_top>0)	{	--_top;	} } template<class T> T& stack<T>::top() {	if(!empty())	{	return _a[_top-1];	} } template<class T> bool stack<T>::empty() {	return (_top==0); } void TestStack() {    stack<int> s1;        s1.push(1);    s1.push(2);    s1.push(3);    s1.push(4);  stack<int> s2(s1);  stack<int> s3=s2;    s1.print();    s2.print();    s3.print();    /*cout<<s.top()<<endl;*/ } int main() {	TestStack();	system("pause");	return 0; }

c++模板实现栈




向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI