C++ Stack size() Function

C++ Stack size() function returns the number of stack elements. The number of stack elements is referred to the size of the stack. The size of the stack element is very important information as based on it we can deduce many other things such as the space required, etc.

Syntax

Parameters

No parameters are passed to the function; it simply gives the size of the stack under reference. Since the function is used to get an idea about the stack size there is no purpose of the argument in the program.

Return value

The number of elements in the stack is returned, which is a measure of the size of the stack. Hence the function has an integer return type as size is an int value.

Example 1

// A simple C++ to demonstrate the use of the size() function in the stack container.

Output:

0. size: 0
1. size: 5
2. size: 4

Example 2

// A simple C++ to demonstrate the use of the size() function in the stack container.

Output:

3

Example 3

// A simple C++ to demonstrate the use of the size() function in the stack container.

Output:

Size of a: 3
Size of b: 2

Complexity

The complexity of the function is constant, the function only returns the size of the stack, which is measured by the number of elements.

Data races

The function accesses the container. The whole stack container is accessed by this function for the value of stack size. As size is measured by the total number of elements present in the stack so whole container is atleast once accessed.

Exception Safety

Guarantee as equivalent to the operations that are performed on the underlying container object is provided.

Next TopicC++ Stack




Latest Courses