文章目錄
- Stack
- 定義方式
- 使用方式
- Queue
- 定義方式
- 使用方式
Stack
Stack是一種容器,是基本的數據結構之一,特點是先進后出。
定義方式
方式一:普通定義方式
stack<int> st1;
方式二:
stack<int,vector<int>> st2;
stack<int,list<int>> st3
注意: 如果沒有為stack指定特定的底層容器,默認情況下使用deque。
使用方式
stack當中常用的成員函數如下:
成員函數 | 功能 |
---|---|
empty | 判斷棧是否為空 |
size | 獲取棧有效元素個數 |
top | 獲取棧頂元素 |
push | 元素入棧 |
pop | 元素出棧 |
swap | 交換兩個棧的數據 |
stack<int, vector<int>> st;st.push(1);st.push(2);st.push(3);st.push(4);cout << st.size() << endl; //4while (!st.empty()){cout << st.top() << " ";st.pop();}cout << endl; //4 3 2 1return 0;
Queue
隊列是一種容器適配器,專門用在具有先進先出操作的上下文環境中,其只能從容器的一端插入元素,另一端提取元素。
定義方式
queue的定義方式
方式一: 使用默認的適配器定義隊列。
queue<int> q1;
方式二: 使用特定的適配器定義隊列。
queue<int, vector<int>> q2;
queue<int, list<int>> q3;
使用方式
成員函數 | 功能 |
---|---|
empty | 判斷隊列是否為空 |
size | 獲取隊列有效元素個數 |
front | 獲取隊頭元素 |
back | 獲取隊尾元素 |
push | 元素入隊列 |
pop | 元素出隊列 |
swap | 交換兩個隊列的數據 |
queue<int, list<int>> q;q.push(1);q.push(2);q.push(3);q.push(4);cout << q.size() << endl; //4while (!q.empty()){cout << q.front() << " ";q.pop();}cout << endl; //1 2 3 4return 0;