C++ Stack Library - top() Function



Description

The C++ function std::stack::top() returns top element of the stack. This is the element which is removed after performing pop operation.

Declaration

Following is the declaration for std::stack::top() function form std::stack header.

C++98

value_type& top();
const value_type& top() const;

C++11

reference& top();
const_reference& top() const;

Parameters

None

Return value

Returns the top element of the stack.

Exceptions

Depends upon underlying container.

Time complexity

Constant i.e. O(1)

Example

The following example shows the usage of std::stack::top() function.

#include <iostream>
#include <stack>

using namespace std;

int main(void) {
   stack<int> s;

   for (int i = 0; i < 5; ++i)
      s.emplace(i + 1);

   while (!s.empty()) {
      cout << s.top() << endl;
      s.pop();
   }

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Stack contents are
5
4
3
2
1
stack.htm
Advertisements