What is Stack in C++ ?

  • Stack is an abstract data structure that contains a collection of elements.
  • It implements the Last In First Out (LIFO) mechanism this element is pushed at the end is popped out first.
  • It uses an encapsulated object of either deque or vector or list as its underlying container, providing a specific set of member functions to access its elements.
  • Stack class is a container adapter and container objects hold data of a similar data type.
  • From various sequence containers we can create a stack.
  • By default, deque container will be used, if there is no container is provided.
  • It cannot be used to manipulate, because container adapters don’t support iterators.
  • In stack Type is the Type of element contained and it can be any valid C++ type or even a user-defined type.
  • In stack containeris the Type of underlying container object.
  • Here three types of member types, they are:
    • Value_type- The first template parameter and donates the element types.
    • Container_type- The second template parameter and denotes the underlying container type.
    • Size_type- It is an unsigned integral type.

Syntax

[pastacode lang=”cpp” manual=”template%20%3Cclass%20Type%2C%20class%20Container%20%3D%20deque%3CType%3E%20%3E%20class%20stack%3B” message=”” highlight=”” provider=”manual”/]

Sample Code

[pastacode lang=”cpp” manual=”%23include%20%3Ciostream%3E%20%20%0A%23include%20%3Cstack%3E%20%20%0Ausing%20namespace%20std%3B%20%20%0Avoid%20newstack(stack%20%3Cint%3E%20ss)%20%20%0A%7B%20%20%0A%20%20%20%20stack%20%3Cint%3E%20sg%20%3D%20ss%3B%20%20%0A%20%20%20%20while%20(!sg.empty())%20%20%0A%20%20%20%20%7B%20%20%0A%20%20%20%20%20%20%20%20cout%20%3C%3C%20’%5Ct’%20%3C%3C%20sg.top()%3B%20%20%0A%20%20%20%20%20%20%20%20sg.pop()%3B%20%20%0A%20%20%20%20%7D%20%20%0A%20%20%20%20cout%20%3C%3C%20’%5Cn’%3B%20%20%0A%7D%20%20%0Aint%20main%20()%20%20%0A%7B%20%20%0A%20%20%20%20stack%20%3Cint%3E%20newst%3B%20%20%0A%20%20%20%20newst.push(55)%3B%20%20%0A%20%20%20%20newst.push(44)%3B%20%20%0A%20%20%20%20newst.push(33)%3B%20%20%0A%20%20%20%20newst.push(22)%3B%20%20%0A%20%20%20%20newst.push(11)%3B%20%20%0A%20%20%0A%20%20%20%20cout%20%3C%3C%20%22The%20stack%20newst%20is%20%3A%20%22%3B%20%20%0A%20%20%20%20newstack(newst)%3B%20%20%0A%20%20%20%20cout%20%3C%3C%20%22%5Cn%20newst.size()%20%3A%20%22%20%3C%3C%20newst.size()%3B%20%20%0A%20%20%20%20cout%20%3C%3C%20%22%5Cn%20newst.top()%20%3A%20%22%20%3C%3C%20newst.top()%3B%20%20%0A%20%20%20%20cout%20%3C%3C%20%22%5Cn%20newst.pop()%20%3A%20%22%3B%20%20%0A%20%20%20%20newst.pop()%3B%20%20%0A%20%20%20%20newstack(newst)%3B%20%20%20%0A%20%20%20%20return%200%3B%20%20%0A%7D%20%20%0A” message=”” highlight=”” provider=”manual”/]

Output

Leave a Reply

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