• June 13, 2021

PHSARIT

Bring Technology Ideas with you

Stack is a standard library which is being use as a type of container adaptor. The data operates in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container. For the references, please visit http://www.cplusplus.com/reference/stack/stack/. Below is the sample code of using Stack in C++ programming language.

    Various examples of Stack
    #include<iostream>
    #include<stack> //libary for using stack
    #include<string> // libary for using string
    using namespace std;
    int main()
    {
    	stack <string> myStudent; // declare stack name is myStudent
    	//-----Insert value into stack-----
    	myStudent.push("Vith");
    	myStudent.push("Them");
    	myStudent.push("Saron");
    	myStudent.push("Vanda");
    	myStudent.push("Chry");
    	myStudent.push("Raksmey");
    	myStudent.push("Vanthan");
    	myStudent.push("Leng");
    	myStudent.push("Meun");
    	myStudent.push("Sela");
    	myStudent.push("Sopheaktra");
    	cout << "There are :\t" << myStudent.size() << "\tstudents in the class." << endl;
    	cout << "The top element of the stack value is: " << myStudent.top() << endl;
    	// show all students using top() and pop() function
    	//cout << "List of students in the class:" << endl;
    	while (!myStudent.empty())
    	{
    		cout << "- " << myStudent.top() << endl;
    		myStudent.pop();
    	}
    	cout << "There are :\t" << myStudent.size() << "\tstudents in the class." << endl;
    	system("pause==0");
    }

    The code the above is using Stack as the standard library to insert the elements which is call name of the students. Then it finds the top of the elements while, it was shown the size of the elements which is returned as the number of the elements. Finally, it print out the list of the students. See the result:

      Result of the compiling code

      Related post