The following table shows commonly used stack APIs:
|
API |
Description |
|
top() |
This returns the top-most value in the stack, that is, the value that was added last |
|
push<data_type>( value ) |
This will push the value provided to the top of the stack |
|
pop() |
This will remove the top-most value from the stack |
|
size() |
This returns the number of values present in the stack |
|
empty() |
This returns true if the stack is empty; otherwise it returns false |
It's time to get our hands dirty; let's write a simple program to use a stack:
#include <iostream>
#include <stack>
#include <iterator>
#include <algorithm>
using namespace std;
int main ( ) {
stack<string> spoken_languages;
spoken_languages.push ( "French" );
spoken_languages.push ( "German" );
spoken_languages.push ( "English" );
spoken_languages.push ( "Hindi" );
spoken_languages.push ( "Sanskrit" );
spoken_languages.push ( "Tamil" );
cout << "nValues in Stack are ..." << endl;
while ( ! spoken_languages.empty() ) {
cout << spoken_languages.top() << endl;
spoken_languages.pop();
}
cout << endl;
return 0;
}
The program can be compiled and the output can be viewed with the following command:
g++ main.cpp -std=c++17
./a.out
The output of the program is as follows:
Values in Stack are ...
Tamil
Kannada
Telugu
Sanskrit
Hindi
English
German
French
From the preceding output, we can see the LIFO behavior of stack.