C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++Stack栈类模版实例

C++Stack栈类模版实例详解

作者:诺谦

这篇文章主要为大家详细介绍了C++Stack栈类模版实例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助

1.栈的介绍

栈的实现方式分为3

栈的函数需要实现如下所示:

本章,我们实现的栈基于动态数组实现,它的父类是我们之前实现的Vector类:

C++ 动态数组模版类Vector实例详解

所以代码实现会非常简单.

2.栈实现

代码如下所示:

#ifndef Stack_H
#define Stack_H
#include "throw.h"
// throw.h里面定义了一个ThrowException抛异常的宏,如下所示:
//#include <iostream>
//using namespace std;
//#define ThrowException(errMsg)  {cout<<__FILE__<<" LINE"<<__LINE__<<": "<<errMsg<<endl; (throw errMsg);}
#include "Vector.h"
template<class T>
class Stack : public Vector<T>
{
public:
    T pop()
    {
        if(Vector<T>::isEmpty()) {        // 如果栈为空,则抛异常
            ThrowException("Stack is empty ...");
        }
        T t = Vector<T>::data()[Vector<T>::length() - 1];
        Vector<T>::resize(Vector<T>::length() - 1);
        return  t;
    }
    // 入栈,实际就是append尾部添加成员
    void push(const T &t)
    {
        Vector<T>::append(t);
    }
    T &top()
    {
        if(Vector<T>::isEmpty()) {
            ThrowException("Stack is empty ...");
        }
        return Vector<T>::data()[Vector<T>::length() - 1];
    }
    const T &top() const
    {
        if(Vector<T>::isEmpty()) {
            ThrowException("Stack is empty ...");
        }
        return Vector<T>::data()[Vector<T>::length() - 1];
    }
};
#endif // Stack_H

3.代码测试

int main(int argc, char *argv[])
{
    Stack<int> stack;
    cout<<"******* current length:"<<stack.length()<<endl;
    for(int i = 0; i < 5; i++) {
        cout<<"stack.push:"<<i<<endl;
        stack.push(i);
    }
    cout<<"******* current length:"<<stack.length()<<endl;
    while(!stack.isEmpty()) {
        cout<<"stack.pop:"<<stack.pop()<<endl;
    }
    return 0;
}

运行打印:

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

您可能感兴趣的文章:
阅读全文