A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://cplusplus.com/reference/stack/stack/top/ below:

public member function

<stack>

std::stack::top
      value_type& top();const value_type& top() const;
      reference top();const_reference top() const;

Access next element

Returns a reference to the top element in the stack.

Since stacks are last-in first-out containers, the top element is the last element inserted into the stack.

This member function effectively calls member back of the underlying container object.



Parameters none

Return value A reference to the top element in the stack.

Member type value_type is the type of the elements in the container (defined as an alias of the first class template parameter, T).

Member types reference and const_reference are aliases of the underlying container's types with the same name.


Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// stack::top
#include <iostream>       // std::cout
#include <stack>          // std::stack

int main ()
{
  std::stack<int> mystack;

  mystack.push(10);
  mystack.push(20);

  mystack.top() -= 5;

  std::cout << "mystack.top() is now " << mystack.top() << '\n';

  return 0;
}

Output:


Complexity Constant (calling back on the underlying container).

Data races The container is accessed (neither the const nor the non-const versions modify the container).
The reference returned can be used to access or modify the top element.

Exception safety Provides the same level of guarantees as the operation performed on the container (no-throw guarantee for standard non-empty containers).

See also See also
stack::pop
Remove top element (public member function)
stack::push
Insert element (public member function)

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4