stack top() in C++ STL
In this article, we will be discussing the working, syntax, and examples of stack::top() function in C++ STL.
What is Stack in C++ STL?
Stacks are the data structure that stores the data in LIFO (Last In First Out) where we do insertion and deletion from the top of the last element inserted. Like a stack of plates, if we want to push a new plate into the stack we insert on the top and if we want to remove the plate from the stack, we then also remove it from the top.
What is stack::top()?
stack::top() function is an inbuilt function in C++ STL, which is defined in <stack> header file. top() is used to access the element at the top of the stack container. In a stack, the top element is the element that is inserted at the last or most recently inserted element.
Syntax
Parameters
The function accepts no parameter(s) −
Return value
This function returns a reference of the element at the top of the stack container.
Name already in use
cpp-docs / docs / standard-library / stack-class.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
17 contributors
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
A template container adaptor class that provides a restriction of functionality limiting access to the element most recently added to some underlying container type. The stack class is used when it is important to be clear that only stack operations are being performed on the container.
Type
The element data type to be stored in the stack.
Container
The type of the underlying container used to implement the stack. The default value is the class deque<Type> .
The elements of class Type stipulated in the first template parameter of a stack object are synonymous with value_type and must match the type of element in the underlying container class Container stipulated by the second template parameter. The Type must be assignable, so that it is possible to copy objects of that type and to assign values to variables of that type.
Suitable underlying container classes for stack include deque , list class, and vector class, or any other sequence container that supports the operations of back , push_back , and pop_back . The underlying container class is encapsulated within the container adaptor, which exposes only the limited set of the sequence container member functions as a public interface.
The stack objects are equality comparable if and only if the elements of class Type are equality comparable and are less-than comparable if and only if the elements of class Type are less-than comparable.
The stack class supports a last-in, first-out (LIFO) data structure. A good analogue to keep in mind would be a stack of plates. Elements (plates) may be inserted, inspected, or removed only from the top of the stack, which is the last element at the end of the base container. The restriction to accessing only the top element is the reason for using the stack class.
The queue class supports a first-in, first-out (FIFO) data structure. A good analogue to keep in mind would be people lining up for a bank teller. Elements (people) may be added to the back of the line and are removed from the front of the line. Both the front and the back of a line may be inspected. The restriction to accessing only the front and back elements in this way is the reason fur using the queue class.
The priority_queue class orders its elements so that the largest element is always at the top position. It supports insertion of an element and the inspection and removal of the top element. A good analogue to keep in mind would be people lining up where they are arranged by age, height, or some other criterion.
| Name | Description |
|---|---|
| stack | Constructs a stack that is empty or that is a copy of a base container object. |
| Name | Description |
|---|---|
| container_type | A type that provides the base container to be adapted by a stack . |
| size_type | An unsigned integer type that can represent the number of elements in a stack . |
| value_type | A type that represents the type of object stored as an element in a stack . |
| Name | Description |
|---|---|
| empty | Tests if the stack is empty. |
| pop | Removes the element from the top of the stack . |
| push | Adds an element to the top of the stack . |
| size | Returns the number of elements in the stack . |
| top | Returns a reference to an element at the top of the stack . |
A type that provides the base container to be adapted.
The type is a synonym for the template parameter Container . All three C++ Standard Library sequence container classes — the vector class, list class, and the default class deque — meet the requirements to be used as the base container for a stack object. User-defined types satisfying these requirements may also be used.
For more information on Container , see the Remarks section of the stack Class topic.
See the example for stack::stack for an example of how to declare and use container_type .
Tests if a stack is empty.
true if the stack is empty; false if the stack is nonempty.
Removes the element from the top of the stack.
The stack must be nonempty to apply the member function. The top of the stack is the position occupied by the most recently added element and is the last element at the end of the container.
Adds an element to the top of the stack.
val
The element added to the top of the stack.
The top of the stack is the position occupied by the most recently added element and is the last element at the end of the container.
Returns the number of elements in the stack.
The current length of the stack.
An unsigned integer type that can represent the number of elements in a stack.
The type is a synonym for size_type of the base container adapted by the stack.
See the example for size for an example of how to declare and use size_type .
Constructs a stack that is empty or that is a copy of a base container class.
right
The container of which the constructed stack is to be a copy.
Returns a reference to an element at the top of the stack.
A reference to the last element in the container at the top of the stack.
The stack must be nonempty to apply the member function. The top of the stack is the position occupied by the most recently added element and is the last element at the end of the container.
If the return value of top is assigned to a const_reference , the stack object cannot be modified. If the return value of top is assigned to a reference , the stack object can be modified.
A type that represents the type of object stored as an element in a stack.
The type is a synonym for value_type of the base container adapted by the stack.
Реализация stack в C
Stack — это линейная структура данных который служит набором элементов с тремя основными операциями.
- Push операция, которая добавляет элемент в stack.
- Pop операция, которая удаляет последний добавленный элемент, который еще не был удален, и
- Peek операция, которая возвращает верхний элемент без изменения stack.
The push а также pop операции происходят только на одном конце структуры, называемом top stack. Порядок, в котором элементы выходят из stack, приводит к его альтернативному названию LIFO (от Last-In, First-Out).
Ниже приведено простое представление stack с push а также pop операции:
Stack может быть реализован с ограниченной емкостью. Если stack заполнен и не содержит достаточно места для push операции, то считается, что stack находится в состоянии переполнения.
Реализация stack с использованием массива:
(Ограниченный) стек можно легко реализовать с помощью массива. Первый элемент stack (то есть самый нижний элемент) сохраняется в 0’th index в массиве (при условии индексации с нуля). Второй элемент будет храниться по индексу 1 и т. д. Мы также поддерживаем переменную top чтобы отслеживать размер stack, записывая общее количество элементов, перемещенных до сих пор. Он указывает на место в массиве, куда должен быть вставлен следующий элемент. Таким образом, сам стек может быть эффективно реализован в виде трехэлементной структуры:
Stack top c что это
Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end called the top of the stack, and an element is removed from the same end only.
stack::top() top() function is used to reference the top(or the newest) element of the stack.
Syntax :
Parameters: No value is needed to pass as the parameter.
Return Value: Direct reference to the top element of the stack container.