#include <iostream> #include <stack> #include <queue> using namespace std; //stack 容器 先進後出 push(壓棧) pop(出棧) top()返回棧頂元素 //stack API //******注意 不提供迭代器 棧不能遍歷,不支持隨機存取,只能通過top從棧頂獲取和刪除元素 //stack 賦值操作 void test() { //初始化 stack<int> s1; stack<int> s2(s1); //stack 存取操作 top()返回棧頂元素 push壓棧 pop()出棧 s1.push(10); s1.push(20); s1.push(30); s1.push(100); cout<<"棧頂元素"<<s1.top()<<endl; s1.pop();//刪除棧頂元素 //打印棧容器的數據(沒有迭代器) //大小操作 empty()判斷堆棧是否爲空 size()返回堆棧的大小 while (!s1.empty()) { cout<<s1.top()<<endl; s1.pop(); } cout<<"s1.size():"<<s1.size()<<endl; } //練習 //1.棧存放對象 //2.棧存放對象指針 //queue 隊列容器 先進先出 一端插入,一端刪除 //push() 入隊操作 pop()出隊操作 同樣的刪除時候沒有返回值,所以在刪除前通過front()返回隊頭元素 back()返回隊尾元素 //和棧一樣 沒有迭代器 不能進行遍歷 不支持隨機訪問 //隊列操作 void test1() { queue<int> q;//創建隊列 q.push(10); q.push(11); q.push(20); q.push(30); //輸出順序 while (!q.empty()) { cout<<q.front()<<endl; cout<<q.back()<<endl; cout<<"-------------------"<<endl; q.pop(); } } //練習 //1.quene容器存放對象指針 //2.quene容器存放stack容器 int main(){ test(); test1(); }
c++ 中的stack 和queue容器
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.