C++ Stacks
Descriptions
A stack stores multiple data’s in a specific order, called LIFO.
LIFO stands for Last in, First Out. To visualize LIFO, think of a pile of plates, where plates are both added and removed from the top. So when removing a plate, it will always be the last one you added. You can only access the element at the top of the stack.
To use a stack, you have to include the <stack> header file
Note: You cannot add elements to the stack at the time of declaration, like you can with vectors
விரிவுரை
ஒரு அடுக்கு என்பது LIFO எனப்படும் ஒரு குறிப்பிட்ட வரிசையில் பல தரவுகளைச் சேமிக்கிறது.
LIFO என்பது கடைசியாக உள்ளே, முதலில் வெளியே என்பதைக் குறிக்கிறது. LIFO ஐ காட்சிப்படுத்த, தட்டுகளின் குவியலை நினைத்துப் பாருங்கள், அங்கு தட்டுகள் இரண்டும் சேர்க்கப்பட்டு மேலிருந்து அகற்றப்படும். எனவே ஒரு தட்டை அகற்றும்போது, அது எப்போதும் நீங்கள் சேர்த்த கடைசி ஒன்றாக இருக்கும். அடுக்கின் மேலே உள்ள உறுப்பை மட்டுமே நீங்கள் அணுக முடியும்.
ஒரு அடுக்கைப் பயன்படுத்த, நீங்கள் <stack> தலைப்பு கோப்பைச் சேர்க்க வேண்டும்.
குறிப்பு: திசையன்களைப் போல, அறிவிப்பின் போது அடுக்கில் கூறுகளைச் சேர்க்க முடியாது
Syntax
// Include the stack library
#include <stack>
stack <string> foods;
type stackName
Add / Remove / Change on Stack
To add /remove data to the stack, use the .push() / .pop() function, after declaring the stack. To change data in stack use .top() function
அடுக்கில் தரவைச் சேர்க்க /நீக்க /மாற்ற
அடுக்கில் தரவைச் சேர்க்க /நீக்க, அடுக்கை அறிவித்த பிறகு, .push() / .pop() செயல்பாட்டைப் பயன்படுத்தவும். அடுக்கில் தரவை மாற்ற .top() செயல்பாட்டைப் பயன்படுத்தவும்.
Example / உதாரணம்
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<string> foods;
// Add a data to stack
foods.push(“RavaDosa”);
foods.push(“Kesari”);
foods.push(“Idly”);
foods.push(“Dosa”);
cout<<foods.top(); // Dosa
cout<<“\n”;
// Remove the LIFO element
foods.pop(); // Dosa
cout<<foods.top(); // Outputs Idly
// Change the value of the first element
foods.top() = “MasalDosa”;
cout<<“\n”;
// show the last item on the stack
cout<<foods.top(); // MasalDosa
// Remove the LIFO element
foods.pop(); // MasalDosa
cout<<“\n”;
cout<<foods.top(); // Outputs Kesari
return 0;
}
Output:
Dosa
Idly
MasalDosa
Kesari
Stack Size
The .size() function is used to find the data count on a stack
ஒரு அடுக்கில் உள்ள தரவு எண்ணிக்கையைக் கண்டறிய .size() செயல்பாடு பயன்படுத்தப்படுகிறது.
Example / உதாரணம்
stack<string> foods ;
cout << foods.size(); // Outputs 0
Stack is Empty
The stack is empty or not can be find by using .empty() function.
The .empty() function returns 1 (true) if the stack is empty and 0 (false)
அடுக்கு காலியாக உள்ளதா இல்லையா என்பதை .empty() செயல்பாட்டைப் பயன்படுத்திக் கண்டறியலாம்.
அடுக்கு காலியாக இருந்தால் .empty() செயல்பாடு 1 (true) ஐயும் 0 (false) ஐயும் வழங்கும்.
Example / உதாரணம்
stack<string> foods ;
cout << foods.empty(); // Outputs 1 true
stack<string> foods ;
foods.push(“Idly”);
foods.push(“Dosa”);
cout << foods.empty(); // Outputs 0 false