stack是堆栈容器,元素遵循先进后出的顺序。
头文件:#include<stack>
一、stack容器的对象构造方法
stack采用模板类实现默认构造
例如stack<T> vecT;
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int> stInt;
stack<float> stFloat;
stack<string> stString;
stInt.push(5);//在栈头添加元素
stInt.pop();//在栈头删除元素
stInt.push(6);//在栈头添加元素
stInt.push(7);//在栈头添加元素
stInt.push(8);//在栈头添加元素
stInt.pop();//在栈头删除元素
while(!stInt.empty())
{
cout<<stInt.top()<<endl;
stInt.pop();//在栈头删除元素
}
//输出7,6
return 0;
}
stack对象的带参构造方式
1、stack<T> st1(st2);拷贝构造函数
2、stack& operator=(const stack &st);重载等号操作符。
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int> stInt1;
stInt1.push(5);//在栈头添加元素
stInt1.pop();//在栈头删除元素
stInt1.push(6);//在栈头添加元素
stInt1.push(7);//在栈头添加元素
stInt1.push(8);//在栈头添加元素
stInt1.pop();//在栈头删除元素
stack<int> stInt2(stInt1);
stack<int> stInt3=stInt1;
while(!stInt1.empty())
{
cout<<stInt1.top()<<endl;
stInt1.pop();//在栈头删除元素
}
//输出7,6
while(!stInt2.empty())
{
cout<<stInt2.top()<<endl;
stInt2.pop();//在栈头删除元素
}
//输出7,6
while(!stInt3.empty())
{
cout<<stInt3.top()<<endl;
stInt3.pop();//在栈头删除元素
}
//输出7,6
return 0;
}
二、stack容器的大小
stack.empty();//判断堆栈是否为空
stack.size();//返回堆栈的大小
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int> stInt1;
stInt1.push(5);//在栈头添加元素
stInt1.pop();//在栈头删除元素
stInt1.push(6);//在栈头添加元素
stInt1.push(7);//在栈头添加元素
stInt1.push(8);//在栈头添加元素
stInt1.pop();//在栈头删除元素
int size=stInt1.size();
cout<<size<<endl;
//输出2
while(!stInt1.empty())
{
cout<<stInt1.top()<<endl;
stInt1.pop();//在栈头删除元素
}
//输出7,6
return 0;
}