目錄
1 -> stack的介紹和使用
1.1 -> stack的介紹
1.2 -> stack的使用
1.3 -> stack的模擬實現
1 -> stack的介紹和使用
1.1 -> stack的介紹
stack的文檔介紹
1. stack是一種容器適配器,專門用在具有后進先出操作的上下文環(huán)境中,其刪除只能從容器的一端進行元素的插入與提取操作。
2. stack是作為容器適配器被實現的,容器適配器即是對特定類封裝作為其底層的容器,并提供一組特定的成員函數來訪問其元素,將特定類作為其底層的,元素特定容器的尾部(即棧頂)被壓入和彈出。
3. stack的底層容器可以是任何標準的容器類模板或一些其他特定的容器類,這些容器類應該支持以下操作:
- empty:?判空操作
- back: 獲取尾部元素操作
- push_back: 尾部插入元素操作
- pop_back: 尾部刪除元素操作
4. 標準容器vector、deque、list均符合這些需求,默認情況下,如果沒有為stack指定特定的底層容器,默認情況下使用deque。
1.2 -> stack的使用
函數說明 | 接口說明 |
stack() | 構造空的棧 |
empty() | 檢測stack是否為空 |
size() | 返回stack中元素的個數 |
top() | 返回棧頂元素的引用 |
push() | 將元素val壓入stack中 |
pop() | 將stack中尾部的元素彈出 |
相關題目:
最小棧
class MinStack
{
public:
void push(int val)
{
st.push(val);
if (Min.empty() || val <= Min.top())
Min.push(val);
}
void pop()
{
if (Min.top() == st.top())
Min.pop();
st.pop();
}
int top()
{
return st.top();
}
int getMin()
{
return Min.top();
}
private:
stack<int> st;
stack<int> Min;
};
棧的壓入、彈出序列
class Solution
{
public:
bool IsPopOrder(vector<int>& pushV, vector<int>& popV)
{
if (pushV.size() != popV.size())
return false;
int in = 0;
int out = 0;
stack<int> st;
while (out < popV.size())
{
while (st.empty() || st.top() != popV[out])
{
if (in < pushV.size())
st.push(pushV[in++]);
else
return false;
}
st.pop();
out++;
}
return true;
}
};
1.3 -> stack的模擬實現
從棧的接口可以看出,棧實際是一種特殊的vector,因此使用vector完全可以模擬實現stack。
#define _CRT_SECURE_NO_WARNINGS 1
#include<vector>
#include<deque>
using namespace std;
namespace fyd
{
template<class T, class Container = deque<T>>
class stack
{
public:
void push(const T& x)
{
_con.push_back(x);
}
void pop()
{
_con.pop_back();
}
const T& top()
{
return _con.back();
}
bool empty()
{
return _con.empty();
}
size_t size()
{
return _con.size();
}
private:
Container _con;
};
}
感謝各位大佬支持?。?!文章來源:http://www.zghlxwxcb.cn/news/detail-850941.html
互三啦?。?!文章來源地址http://www.zghlxwxcb.cn/news/detail-850941.html
到了這里,關于【C++航海王:追尋羅杰的編程之路】stack的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!