数据结构—顺序栈

本程序在VS2010及以上编译时可能会出现错误:

error C4996: 'std::_Copy_impl': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'

1> d:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility(2113) : 参见"std::_Copy_impl"的声明

请按照一下步骤处理:

注:引起该问题的主要原因是新的vs版本处于安全性的角度考虑,禁用了老版本的copy函数

MyUtil.h头文件源代码:

#ifndef _MYUTIL_H

#define _MYUTIL_H

 

#include<algorithm>

template <class T>

void ChangeSize1D(T* &a, const int oldSize, const int newSize)

{

    if (newSize<0)

        throw "New length must be >=0";

    T* temp = new T[newSize];

    int number = min(oldSize, newSize);

    std::copy(a, a + number, temp);

    delete[] a;

    a = temp;

}

 

#endif

 

MyStack.h头文件源代码:

#ifndef _MYSTACK_H

#define _MYSTACK_H

 

#include"MyUtil.h"

 

template<class T>

class MyStack

{

public:

    MyStack(int stackCapacity = 10);

    ~MyStack();

 

    bool IsEmpty() const;

    T& Top() const;    //显示栈顶元素

    void Push(const T& item);    //入栈

    void Pop();        //删除栈顶元素

private:

    T* stack;

    int top;    //记录栈顶的位置

    int capacity;    //栈的容量

};

 

 

//构造函数

template<class T>

MyStack<T>::MyStack(int stackCapacity = 10):capacity(stackCapacity)

{

    if (capacity<1)

        throw "stack capacity must be > 0";

    stack = new T[capacity];

 

}

 

//析构函数

template<class T>

MyStack<T>::~MyStack()

{

    delete[] stack;

 

}

 

//向栈中压入数据

template<class T>

void MyStack<T>::Push(const T& item)

{

    if (top == capacity - 1)    //如果栈满

    {

        ChangeSize1D(stack, capacity, 2 * capacity);    //扩大数组原来的两倍

        capacity = 2 * capacity;

    }

    stack[++top] = item;

}

 

//判断堆中是否为空

template<class T>

inline bool MyStack<T>::IsEmpty() const

{

    return top == -1;    //很高超的写法

}

 

//返回栈顶元素

template<class T>

inline T& MyStack<T>::Top() const

{

    if (IsEmpty())

        throw "Stack is empty";

    return stack[top];

}

 

//删除栈顶元素

template<class T>

void MyStack<T>::Pop()

{

    if (IsEmpty())

        throw "Stack is empty.Cannot delete";

    stack[top--].~T();    //调用元素的析构函数

}

 

#endif

 

主程序源代码:

#include<iostream>

#include"MyStack.h"

#include"MyUtil.h"

 

using namespace std;

 

int main()

{

    MyStack<int> st;

    st.Push(99);

    st.Push(22);

    st.Push(18);

    st.Push(67);

    cout << st.Top() << endl;

    st.Pop();

    cout << st.Top() << endl;

    st.Pop();

    cout << st.Top() << endl;

    st.Pop();

    cout << st.Top() << endl;

    return 0;

}

posted @ 2016-04-16 23:25  硫酸亚铜  阅读(161)  评论(0编辑  收藏  举报