C++ – What are stacks used for? Why are they in C++

cstack

I've been reviewing C++ with the book Practical C++ Programming, and came across these things called Stacks. Defined in the book, it is defined as an algorithm for storing data.

From what I've seen in the book, it looks a lot like assembly…I also recall reading something about something that is 16 bit.

So my question: What are stacks used for, are they still useful or is it an old method of doing something that can be done more simply and efficiently with 32/64 bit computers? I'm just really confused about what purpose stacks serve.


Edit: Since my question is so vague, I'll rephrase it… What is a stack, and when should it be used.

Best Answer

Stacks are not a method, but rather a data structure, last in, first out (LIFO).

In C++, std::stack<> is a class template whose data can be any type. There are many situations where last in, first out is exactly what you need.

An example are virtual machines or interpreters that utilise a stack architecture to save the running state during execution of functions/procedures. Consider the following the interpreter of a language where sub-procedures may not change the state of the caller:

std::stack<RunState> state;
Instruction i = fetch();

switch (i.type()) {
case Instruction.Call:
    state.push (state.top());
    break;
case Instruction.Return:
    state.pop();
    break;
...
}

Wikipedia has more examples for the use of stack data structures. Some sorting problems are solved relatively easily with stacks.

As with all data structures, and C++ has quite some of them (lists, queues, sets, maps (a.k.a. associative arrays, a.k.a. dictionaries), arrays/vectors, and more), you may not need them now and maybe not even in 2 years, but you should know about them, their properties, advantages, disadvantages, and when it is the right moment to use them.