C++ STL中的堆栈是否暴露了底层容器的任何迭代器,还是应该直接使用该容器?std :: stack暴露迭代器吗?
29
A
回答
34
根据堆栈的定义,堆栈没有迭代器。如果你需要迭代器堆栈,你需要自己在其他容器(std :: list,std :: vector等)之上实现它。 Stack doc is here。
P.S.根据我从Iraimbilanja得到的评论,std :: stack默认使用std :: deque来实现。
1
10
如果您需要使用迭代器的堆栈,您有两种选择。 std :: vector使用push_back(),pop_back()。 std :: deque与push_back()/ pop_back()或push_front()/ pop_front()。
0
std::stack
确实通过其受保护的接口将其底层容器(因此迭代器)公开到的子类。所以如果你想访问它们,你可以稍微扩展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';
}
输出:
2 5 3 7 9
相关问题
- 1. 暴露私人范围的Boost.BiMap迭代
- 2. 能从只暴露迭代器的“readNext”部分的对象创建流吗?
- 3. 如何在不暴露容器的情况下公开迭代器?
- 4. std :: move()使迭代器失效吗?
- 5. 如何从std :: stack <T,std :: vector <T>>获取非const迭代器?
- 6. std :: shared_ptr迭代器
- 7. 暴露std :: vector <double>与boost.python
- 8. 暴露std :: vector <struct> with boost.python
- 9. java属性 - 暴露还是不暴露?
- 10. 在复合组件中迭代时暴露列表项目
- 11. 斯卡拉:通过发电机暴露一个JDBC结果(迭代器)
- 12. 暴露在Drupal
- 13. 暴露在Drupal
- 14. std :: list vs std :: vector迭代
- 15. 加密暴露在比萨吗?
- 16. 组件暴露给所有用户吗?
- 17. 暴露IP地址安全吗?
- 18. 暴露C++函数到Python
- 19. 迭代器只能迭代一次吗?
- 20. 代理/存根是否暴露接口?
- 21. 暴露集合的高效替代品
- 22. 由AWS Elastic暴露的源代码Beanstalk
- 23. std ::队列迭代
- 24. std :: forward_list :: push_front迭代
- 25. WCF暴露为RESTful
- 26. WebClient不暴露downloadFile()
- 27. 暴露VisualOffsets属性
- 28. 暴露net.tcp端点
- 29. 暴露一个TStringList
- 30. 的std ::列表<std::string> ::迭代器的std :: string
1。还要注意std :: stack默认使用std :: deque作为它的实现,所以这对于iterstack的默认实现也是一个不错的选择。另一个问题是,*为什么*你想要一个可迭代的堆栈,而不是,比如说,一个直接的双层队列 – 2009-02-08 08:18:09