C++ STL में Stack क्या है?
Stack एक डेटा संरचना है जो डेटा को LIFO (Last In First Out) क्रम में संग्रहीत करती है, जहां सम्मिलन और विलोपन अंतिम सम्मिलित तत्व के शीर्ष से होता है। जैसे प्लेटों का ढेर: नई प्लेट डालने के लिए हम शीर्ष पर रखते हैं और हटाने के लिए भी शीर्ष से ही हटाते हैं।
stack::emplace() क्या है?
stack::emplace() C++ STL में एक अंतर्निहित फंक्शन है, जो <stack> हेडर फाइल में परिभाषित है। emplace() का उपयोग स्टैक कंटेनर में एक तत्व को निर्मित और सम्मिलित करने के लिए किया जाता है।
जब यह फंक्शन चलता है, तो यह स्टैक के शीर्ष पर एक नया तत्व सम्मिलित करता है और नए सम्मिलित तत्व को शीर्ष तत्व बना देता है। यह फंक्शन शीर्ष पर नया तत्व सम्मिलित करने के लिए emplace_back को कॉल करता है।
सिंटैक्स
stack_name.emplace(Args& args);
पैरामीटर्स
args - ये वे आर्गुमेंट हैं जिन्हें हम emplace करना चाहते हैं।
रिटर्न वैल्यू
यह फंक्शन कुछ भी वापस नहीं करता।
उदाहरण
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> stck;
stck.emplace(10);
stck.emplace(20);
stck.emplace(30);
stck.emplace(40);
stck.emplace(50);
stck.emplace(60);
cout << "Elements in stack are: ";
while (!stck.empty()) {
cout << stck.top() << " ";
stck.pop();
}
return 0;
}
आउटपुट
उपरोक्त कोड चलाने पर निम्न आउटपुट उत्पन्न होगा:
Elements in stack are: 60 50 40 30 20 10
एक और उदाहरण
#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<int> stck;
int total = 0;
stck.emplace(10);
stck.emplace(20);
stck.emplace(30);
stck.emplace(40);
stck.emplace(50);
stck.emplace(60);
cout << "Elements in stack are: ";
while (!stck.empty()) {
cout << stck.top() << " ";
stck.pop();
total++;
}
cout << "\nTotal number of elements in stack are: " << total;
return 0;
}
आउटपुट
Elements in stack are: 60 50 40 30 20 10 Total number of elements in stack are: 6