堆疊與佇列的使用 (C++)
阿新 • • 發佈:2019-02-04
堆疊 stack 先進後出
stack類中包含以下幾個成員函式:
- empty() 堆疊為空則返回真
- pop() 移除棧頂元素(不會返回棧頂元素的值)
- push() 在棧頂增加元素
- size() 返回棧中元素數目
- top() 返回棧頂元素
例子:
# include <iostream> # include <stack> using namespace std; struct chess{ int row; int col; }; int main() { stack<chess> st; chess ch[1000]; for(int i=0;i<10;i++){ ch[i].row = i; ch[i].col = i+1; st.push(ch[i]); } cout<<st.top().row<<" "; cout<<st.top().col<<endl; st.pop(); cout<<st.top().row<<" "; cout<<st.top().col<<endl; return 0; }
佇列 queue 先進先出
queue類包含以下成員函式:
- back()返回最後一個元素
- empty()如果佇列空則返回真
- front()返回第一個元素
- pop()刪除第一個元素
- push()在末尾加入一個元素
- size()返回佇列中元素的個數
例子:
# include <iostream> # include <queue> using namespace std; struct chess{ int row; int col; }; int main() { queue<chess> que; chess ch[1000]; for(int i=0;i<10;i++){ ch[i].row = i; ch[i].col = i+1; que.push(ch[i]); } cout<<que.front().row<<" "; cout<<que.front().col<<endl; que.pop(); cout<<que.front().row<<" "; cout<<que.front().col<<endl; return 0; }