stack::top and stack::empty
Illustrates how to use the stack::top and stack::empty STL functions in Visual C++.
template<class _TYPE, class _C, class _A>
value_type& stack::top( );
template<class _TYPE, class _C, class _A>
const value_type& stack::top( ) const;
template<class _TYPE, class _C, class _A>
bool stack::empty( ) const;
Remarks
Note
The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.
The top function returns the topmost element of the stack. You should ensure that there are one or more elements on the stack before calling the top function. The first version of the top function returns a reference to the element of the top of the stack, allowing you to modify the value. The second function returns a constant reference, ensuring that you do not accidentally modify the stack. The empty function returns true if there are no elements in the stack. If there are one or more elements, the function will return false. You should use the empty function to verify that there are elements left on the stack before calling the top function.
Example
// StackTopEmpty.cpp
// compile with: /EHsc
// Illustrates how to use the top function to
// retrieve the last element of the controlled
// sequence. It also illustrates how to use the
// empty function to loop though the stack.
//
// Functions:
//
// top : returns the top element of the stack.
// empty : returns true if the stack has 0 elements.
//////////////////////////////////////////////////////////////////////
#pragma warning(disable:4786)
#include <stack>
#include <iostream>
using namespace std ;
typedef stack<int> STACK_INT;
int main()
{
STACK_INT stack1;
cout << "stack1.empty() returned " <<
(stack1.empty()? "true": "false") << endl; // Function 3
cout << "stack1.push(2)" << endl;
stack1.push(2);
if (!stack1.empty()) // Function 3
cout << "stack1.top() returned " <<
stack1.top() << endl; // Function 1
cout << "stack1.push(5)" << endl;
stack1.push(5);
if (!stack1.empty()) // Function 3
cout << "stack1.top() returned " <<
stack1.top() << endl; // Function 1
cout << "stack1.push(11)" << endl;
stack1.push(11);
if (!stack1.empty()) // Function 3
cout << "stack1.top() returned " <<
stack1.top() << endl; // Function 1
// Modify the top item. Set it to 6.
if (!stack1.empty()) { // Function 3
cout << "stack1.top()=6;" << endl;
stack1.top()=6; // Function 1
}
// Repeat until stack is empty
while (!stack1.empty()) { // Function 3
const int& t=stack1.top(); // Function 2
cout << "stack1.top() returned " << t << endl;
cout << "stack1.pop()" << endl;
stack1.pop();
}
}
stack1.empty() returned true stack1.push(2) stack1.top() returned 2 stack1.push(5) stack1.top() returned 5 stack1.push(11) stack1.top() returned 11 stack1.top()=6; stack1.top() returned 6 stack1.pop() stack1.top() returned 5 stack1.pop() stack1.top() returned 2 stack1.pop()
Requirements
Header: <stack>