⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stack.cpp

📁 C++ sample code, for the book: C++ black book, including templates, exceptional handling.
💻 CPP
字号:
#include <iostream>
using namespace std;

class stack_class {
    int max_values;
    int *data_buffer;
    int stack_top;     // stack_top = -1 --> stack is empty
public:
    stack_class(int mem_required);
    ~stack_class(void);
    int pop(int & pop_to);
    int push(int push_this);
};

stack_class::stack_class(int mem_required)
{
    stack_top = -1;         // Can't initalize in a class def'n.
    max_values = mem_required;
    data_buffer = new int[mem_required];
}

stack_class::~stack_class(void)       // Destructor: get rid of memory
{
    cout << "Deallocating memory.\n";
    delete[] data_buffer;
}

int stack_class::pop(int & pop_to)
{
    if(stack_top == -1)      // Stack is empty -- return error
        return 0;
    else                     // Else return data
        pop_to = data_buffer[stack_top--];
        return 1;
}

int stack_class::push(int push_this)
{
    if(stack_top >= max_values) // Stack is full -- return error
        return 0;
    else                            // Else store data
        data_buffer[++stack_top] = push_this;
        return 1;
}

int main()
{
    stack_class stack(200);
    int loop_index, popped_value;

    cout << "Pushing values now...\n";      // Push values first

    for(loop_index = 0; loop_index < 10; loop_index++){
        stack.push(loop_index);
        cout << "Pushed value--> " << loop_index << "\n";
    }

    cout << "Popping values now...\n";      // Now pop values

    while(stack.pop(popped_value)){
        cout << "Popped value--> " << popped_value << "\n";
    }

    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -