c++stack(堆栈)是一个容器的改编,它实现了一个先进后出的数据结构(FILO)
使用该容器时需要包含#include头文件;
定义stack对象的示例代码如下:
stacks1;
stacks2;
stack的基本操作有:
1.入栈:如s.push(x);
2.出栈:如 s.pop().注意:出栈操作只是删除栈顶的元素,并不返回该元素;
3.访问栈顶:如s.top();
4.判断栈空:如s.empty().当栈空时返回true;
5.访问栈中的元素个数,如s.size();
示例:
#include
#include
using namespace std;
int main()
{
//定义一个栈
stack s;
for (int i = 0; i < 10; i++)
{
s.push(i);
}
cout << "The number of the number is: " << s.size() << endl;
while (!s.empty())
{
cout << s.top() << endl;
s.pop();
}
return 0;
}