无涯教程-C++ Stack - size函数

189 阅读1分钟

C++ Stack size()函数返回堆栈元素的数量。堆栈元素的数量是指堆栈的大小。堆栈元素的大小是非常重要的信息,基于它我们可以推断出许多其他内容,例如所需的空间等。

size - 语法

size_type size() const

size - 参数

没有参数传递给函数;它只是给出了参考堆栈的大小。由于该函数用于了解堆栈大小,因此程序中没有自变量的目的。

size - 返回值

返回堆栈中元素的数量,它是堆栈大小的度量。因此,该函数具有整数返回类型,因为size是一个int值。

size - 例子1

//一个简单的C++来演示在堆栈集合中使用size()函数。

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

输出:

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

size - 例子2

//一个简单的C++来演示在堆栈集合中使用size()函数。

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

输出:

3

size - 例子3

//一个简单的C++来演示在堆栈集合中使用size()函数。

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

输出:

Size of a: 3
Size of b: 2

参考链接

www.learnfk.com/c++/cpp-sta…