C++ stack 容器
开发工具与关键技术:Visual Studio、C++
作者:张国军
撰写时间:2019年07月17日
stack 是堆栈容器,是一种“先进后出”的容器。
stack 是简单地装饰 deque 容器而成为另外的一种容器。#include
stack 对象的默认构造
//stack 对象的默认构造形式: stack stkT;
stack stkInt; //一个存放 int 的 stack 容器。
stack stkFloat; //一个存放 float 的 stack 容器。
stack stkString; //一个存放 string 的 stack 容器。
stack 对象的拷贝构造与赋值
#include <iostream>
#include <stack>
using namespace std;
template<class T>
void stackshow(stack<T>& s) {
while (!s.empty())//判断是否为空取反
{
int tmp = s.top(); //获取栈顶元素
cout << tmp << " ";
s.pop(); //弹出栈顶元素
}
cout << endl;
}
void main()
{
stack<int> stkIntA;
stkIntA.push(1); //push()进栈
stkIntA.push(3);
stkIntA.push(5);
stkIntA.push(7);
stkIntA.push(9);
stack<int> stkIntB(stkIntA); //拷贝构造
stack<int> stkIntC;
stkIntC = stkIntA; //赋值
cout << "-------------stkIntA------------" << endl;
stackshow(stkIntA);
cout << "-------------stkIntB------------" << endl;
stackshow(stkIntB);
cout << "-------------stkIntC------------" << endl;
stackshow(stkIntC);
}
stack 的数据存取
#include <iostream>
#include <stack>
using namespace std;
template<class T>
void stackshow(stack<T>& s) {
while (!s.empty())//判断是否为空取反
{
int tmp = s.top(); //获取栈顶元素
cout << tmp << " ";
s.pop(); //弹出栈顶元素
}
cout << endl;
}
void main()
{
stack<int> stkIntA;
stkIntA.push(1);
stkIntA.push(3);
stkIntA.push(5);
stkIntA.push(7);
stkIntA.push(9);
int iTop = stkIntA.top(); //9
stkIntA.top() = 19;
stackshow(stkIntA);
}
stack 的大小
#include <iostream>
#include <stack>
using namespace std;
void main()
{
stack<int> stkIntA;
stkIntA.push(1);
stkIntA.push(3);
stkIntA.push(5);
stkIntA.push(7);
stkIntA.push(9);
int iSize = 0;
if (!stkIntA.empty())
{
iSize = stkIntA.size(); //5
}
cout << "栈的大小为:" << iSize<<endl;
}