Coding

C++ stack

In some sample code, you may see a reference to stack.

This is a type of data structure, that according to cpp-reference :

The std::stack class is a container adapter that gives the programmer the functionality of a stack - specifically, a LIFO (last-in, first-out) data structure.

This is actually a wrapper for another container class.

An example of it’s use is:

// Make a stack for us to play with
auto stack_of_numbers = std::stack<int>();

// Push numeric values on to the stack
for (auto i = 1; i <= 10; i++)
  stack_of_numbers.push(i);

// Display the top of the stack, then pop it, reducing the size of the stack by 1
while (!stack_of_numbers.empty())
{
  std::cout << stack_of_numbers.top() << "\n";
  stack_of_numbers.pop();
}

// Little message to show that we got rid of the contents
if (stack_of_numbers.empty())
  std::cout << "Is empty\n";

// Now confirming the size of the empty stack
std::cout << "Stack size: " << stack_of_numbers.size() << "\n";

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.