English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and example of Stack size() function

C++ STL Stack (Stack)

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

Syntax

size_type size() const

Parameter

No parameters are passed to the function; it just gives the size of the reference stack. Since the function is used to understand the stack size, there is no purpose of the variable in the program.

Return value

The size() function returns the number of elements in the stack, which is a measure of the stack size. Therefore, the function has an integer return type because size is an int value.

example1

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

#include <iostream>
#include <stack>
using namespace std;
int main()
{
	stack<int> newstack;
	cout << "0. size: " << newstack.size();
	for(int j=0; j<5; j++)
	newstack.push(j);
	cout << \n;
	cout << "1. size: " << newstack.size();
	newstack.pop();
	cout << \n;
	cout << "2. size: " << newstack.size();
	return 0;
}

Output:

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

example2

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

#include <iostream>
#include <stack>
using namespace std;
int main()
{
	stack<int> newstack;
	newstack.push(23);
	newstack.push(46);
	newstack.push(69);
	cout << newstack.size();
	return 0;
}

Output:

3

example3

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

#include <iostream>
#include <stack>
using namespace std;
int main()
{
	stack<int> a, b;
	a.push(5); a.push(8); a.push(50);
	b.push(132); b.push(45);
	cout << "a size: " << a.size();
	cout << "\n  Size of b: " << b.size();
	return 0;
}

Output:

Size of a: 3
Size of b: 2

Complex

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

Data RACE

This function accesses the container. It accesses the entire stack container through this function to get the size of the stack. Since the size is measured by the total number of elements in the stack, the entire container is at least accessed once.

Exception Safety

It provides the same guarantees as operations performed on underlying container objects.

C++ STL Stack (Stack)