[C++]模板类的使用(Stack)

模板类的使用

// stcktp1.h -- modified Stack template
#ifndef STCKTP1_H_
#define STCKTP1_H_

template 
class Stack
{
private:
    enum { SIZE = 10 };   // default size
    int stacksize;
    Type * items;       // holds stack items
    int top;            // index for top stack item
public:

    explicit Stack(int ss = SIZE);
    Stack(const Stack & st);
    ~Stack() { delete[] items; }

    bool isempty() { return top == 0; }
    bool isfull() { return top == stacksize; }
    bool push(const Type & item);   // add item to stack
    bool pop(Type & item);          // pop top into item

    Stack & operator=(const Stack & st);
};

template 
Stack::Stack(int ss) : stacksize(ss), top(0)
{
    items = new Type[stacksize];
}

// 拷贝构造函数
template 
Stack::Stack(const Stack & st)
{
    stacksize = st.stacksize;
    top = st.top;
    items = new Type[stacksize];
    for (int i = 0; i < top; i++)
        items[i] = st.items[i];
}

template 
bool Stack::push(const Type & item)
{
    if (top < stacksize)
    {
        items[top++] = item;
        return true;
    }
    else
        return false;
}

template 
bool Stack::pop(Type & item)
{
    if (top > 0)
    {
        item = items[--top];
        return true;
    }
    else
        return false;
}

template 
Stack & Stack::operator=(const Stack & st)
{
    // 如果是自己本身,直接返回
    if (this == &st) {
        return *this;
    }

    // 删除以前的items
    delete[] items;
    stacksize = st.stacksize;
    top = st.top;
    items = new Type[stacksize];
    for (int i = 0; i < top; i++)
    {
        items[i] = st.items[i];
    }
    return *this;
}

#endif

测试类

// stkoptr1.cpp -- testing stack of pointers
#include 
#include       // for rand(), srand()
#include         // for time()
#include "../inc/stcktp1.h"

const int Num = 10;
int main()
{
    std::srand(std::time(0));   // randomize rand()
    std::cout << "Please enter stack size: ";
    int stacksize;
    std::cin >> stacksize;
    // create an empty stack with stacksize slots
    Stack st(stacksize);

    // in basket
    const char * in[Num] = {
            " 1: Hank Gilgamesh", " 2: Kiki Ishtar",
            " 3: Betty Rocker", " 4: Ian Flagranti",
            " 5: Wolfgang Kibble", " 6: Portia Koop",
            " 7: Joy Almondo", " 8: Xaverie Paprika",
            " 9: Juan Moore", "10: Misha Mache"
    };
    // out basket
    const char * out[Num];

    int processed = 0;
    int nextin = 0;
    while (processed < Num)
    {
        if (st.isempty())
            st.push(in[nextin++]);
        else if (st.isfull())
            st.pop(out[processed++]);
        else if (std::rand() % 2 && nextin < Num) // 50-50 chance
            st.push(in[nextin++]);
        else
            st.pop(out[processed++]);
    }
    for (int i = 0; i < Num; i++)
        std::cout << out[i] << std::endl;

    std::cout << "Bye\n";
    return 0;
}

你可能感兴趣的:([C++]模板类的使用(Stack))