📜  C++ STL-stack(1)

📅  最后修改于: 2023-12-03 15:13:56.148000             🧑  作者: Mango

C++ STL - Stack

Introduction

In C++, the Standard Template Library (STL) provides a container called Stack. It is an adapter container, meaning it is used to adapt an underlying container into the form of a stack. It follows the LIFO (Last-In-First-Out) principle, where the element that is inserted last is the first element to be removed from the stack.

Declaration

The syntax to declare a stack is as follows:

stack<data_type> stack_name;

Here, data_type is the type of data you want to store in the stack and stack_name is the name of the stack.

Operations

The following are the commonly used operations on the stack:

Push

The push() function is used to insert an element onto the top of the stack.

stack_name.push(element);

Here, element is the element you want to insert onto the top of the stack.

Pop

The pop() function is used to remove the top element from the stack.

stack_name.pop();
Top

The top() function returns the top element of the stack, without removing it from the stack.

stack_name.top();
Size

The size() function returns the number of elements currently present in the stack.

stack_name.size();
Empty

The empty() function returns a boolean value indicating whether the stack is empty.

stack_name.empty();
Example

The following code gives an example implementation of a stack, where you can enter a set of numbers and it will return the sum of the numbers:

#include <iostream>
#include <stack>

using namespace std;

int main() {
    stack<int> s;
    int n, sum = 0;
    cout << "Enter the number of elements: ";
    cin >> n;
    cout << "Enter " << n << " elements: ";
    for (int i = 0; i < n; i++) {
        int x;
        cin >> x;
        s.push(x);
    }
    while (!s.empty()) {
        sum += s.top();
        s.pop();
    }
    cout << "The sum is: " << sum << endl;
    return 0;
}
Conclusion

The Stack container in C++ STL is a simple and easy-to-use container that can be used in a variety of applications where a LIFO data structure is required. Its easy-to-use functions like push(), pop(), top(), size() and empty() make it a popular choice among programmers.