Stack簡介
1.stack對象的默認構造
stack采用模板類實現, stack對象的默認構造形式: stack <T> stkT;
stack <int> stkInt; //一個存放int的stack容器。
stack <float> stkFloat; //一個存放float的stack容器。
stack <string> stkString; //一個存放string的stack容器。
//尖括號內還可以設置指針類型或自定義類型。
2.stack的push()與pop()方法
#include<iostream>
using namespace std;
#include <stack>
void objPlay2()
{
stack<int> stkInt;
stkInt.push(1); //放進去1
stkInt.push(3); //放進去3
stkInt.pop(); //彈出來一個元素
stkInt.push(5); //放進去5
stkInt.push(7); //放進去7
stkInt.push(9); //放進去9 此時元素就是1,5,7,9
stkInt.pop(); //彈出來一個元素
stkInt.pop();//彈出來一個元素 此時元素就是1,5
}
int main()
{
objPlay2();
return 0;
}
void objPlay3()
{
stack<int> stkIntA;
stkIntA.push(1);
stkIntA.push(3);
stkIntA.push(5);
stkIntA.push(7);
stkIntA.push(9);
stack<int> stkIntB(stkIntA); //拷貝構造
stack<int> stkIntC;
stkIntC = stkIntA; //賦值
}
4.stack的數據存取
void objPlay4()
{
stack<int> stkIntA;
stkIntA.push(1);
stkIntA.push(3);
stkIntA.push(5);
stkIntA.push(7);
stkIntA.push(9);
int iTop = stkIntA.top(); //獲取棧頂元素,那就是9,top只是獲取棧頂元素,pop是彈出棧頂元素
stkIntA.top() = 19; //19
}
void objPlay5()
{
stack<int> stkIntA;
stkIntA.push(1);
stkIntA.push(3);
stkIntA.push(5);
stkIntA.push(7);
stkIntA.push(9);
if (!stkIntA.empty())
{
int iSize = stkIntA.size(); //5個元素
}
}
下面是以上的所有代碼:
#include<iostream>
using namespace std;
#include <stack>
void objPlay2()
{
stack<int> stkInt;
stkInt.push(1); //放進去1
stkInt.push(3); //放進去3
stkInt.pop(); //彈出來一個元素
stkInt.push(5); //放進去5
stkInt.push(7); //放進去7
stkInt.push(9); //放進去9 此時元素就是1,5,7,9
stkInt.pop(); //彈出來一個元素
stkInt.pop();//彈出來一個元素 此時元素就是1,5
}
void objPlay3()
{
stack<int> stkIntA;
stkIntA.push(1);
stkIntA.push(3);
stkIntA.push(5);
stkIntA.push(7);
stkIntA.push(9);
stack<int> stkIntB(stkIntA); //拷貝構造
stack<int> stkIntC;
stkIntC = stkIntA; //賦值
}
void objPlay4()
{
stack<int> stkIntA;
stkIntA.push(1);
stkIntA.push(3);
stkIntA.push(5);
stkIntA.push(7);
stkIntA.push(9);
int iTop = stkIntA.top(); //獲取棧頂元素,那就是9,top只是獲取棧頂元素,pop是彈出棧頂元素
stkIntA.top() = 19; //19
}
void objPlay5()
{
stack<int> stkIntA;
stkIntA.push(1);
stkIntA.push(3);
stkIntA.push(5);
stkIntA.push(7);
stkIntA.push(9);
if (!stkIntA.empty())
{
int iSize = stkIntA.size(); //5個元素
}
}
int main()
{
objPlay2();
objPlay3();
objPlay4();
objPlay5();
return 0;
}
轉載自http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_stl_004.html