-
stack栈是先进后出的,只能在顶部进行插入和删除
不能通过size()来进行遍历,因为从pop顶端元素后,size值发生了变化
所以需要empty()、top()和pop()结合达到遍历效果(但栈中元素会被删除)

-
构造函数
stack stk; //默认构造函数
stack(const stack &stk); //拷贝构造函数 -
赋值操作
stack& operator=(const stack &stk); //重载赋值操作符 -
数据存取
push(elem);//栈顶添加元素
pop(); //从栈顶移除元素
top(); //返回栈顶元素 -
大小操作
empty(); //判断堆栈是否为空
size(); //返回栈的大小
#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
#include <stack>
using namespace std;
void test1()
{
stack<int> stk;
stk.push(10);
stk.push(20);
stk.push(30);
stk.push(40);
while(!stk.empty())
{
cout<<stk.top()<<" ";
stk.pop();
}
cout<<endl;
cout<<"size:"<<stk.size()<<endl;
}
int main()
{
test1();
return 0;
}
本文详细解析了栈数据结构的工作原理,包括其先进后出的特点,以及如何使用empty(), top()和pop()方法进行遍历。并通过一个C++示例展示了栈的基本操作,如push, pop, top和size等。
849

被折叠的 条评论
为什么被折叠?



