Dra*_*sha 37
根据堆栈的定义,堆栈没有迭代器.如果你需要使用迭代器堆栈,你需要在其他容器(std :: list,std :: vector等)之上自己实现它. Stack doc就在这里.
PS根据我从Iraimbilanja得到的评论,std :: stack默认使用std :: deque进行实现.
pax*_*977 12
如果需要带迭代器的堆栈,则有两种选择.使用push_back(),pop_back()的std :: vector.std :: deque与push_back()/ pop_back()或push_front()/ pop_front().
在std::stack不暴露其底层容器(因此迭代),以亚类通过其保护的接口。所述std::stack的底层容器对象对应于(被保护)的数据成员c。所以如果你想访问它们,你可以扩展std::stack一点。
template<typename T, typename Container = std::deque<T>>
class iterable_stack
: public std::stack<T, Container>
{
using std::stack<T, Container>::c;
public:
// expose just the iterators of the underlying container
auto begin() { return std::begin(c); }
auto end() { return std::end(c); }
auto begin() const { return std::begin(c); }
auto end() const { return std::end(c); }
};
int main()
{
iterable_stack<int> st;
st.push(2);
st.push(5);
st.push(3);
st.push(7);
st.push(9);
for(auto i: st)
std::cout << i << ' ';
std::cout << '\n';
}
Run Code Online (Sandbox Code Playgroud)
输出:
2 5 3 7 9
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27556 次 |
| 最近记录: |