是否可以在C++中遍历 std::stack
?
使用以下方法遍历不适用。因为 std::stack
没有成员 end
。
std::stack<int> foo;
// ..
for (__typeof(foo.begin()) it = foo.begin(); it != foo.end(); it++)
{
// ...
}
原文由 user1857492 发布,翻译遵循 CC BY-SA 4.0 许可协议
是否可以在C++中遍历 std::stack
?
使用以下方法遍历不适用。因为 std::stack
没有成员 end
。
std::stack<int> foo;
// ..
for (__typeof(foo.begin()) it = foo.begin(); it != foo.end(); it++)
{
// ...
}
原文由 user1857492 发布,翻译遵循 CC BY-SA 4.0 许可协议
我不会这样做,但是您可以在不使用指针转换弹出的情况下获得堆栈值,这对编译的类如何存储在内存中做出了一些假设,这通常不是一个好主意。
只要您不更改默认的底层容器 std::deque
,您就可以:
std::stack<int>s;
s.push(1234);
s.push(789);
std::deque<int>* d;
d = (std::deque<int>*)&s;
cout << (*d)[0] << endl;
cout << (*d)[1] << endl;
在不弹出堆栈的情况下输出:
1234
789
原文由 Kaaf 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
不。堆栈是一种数据结构,当您有兴趣将元素放在顶部并从顶部获取元素时,您应该使用它。如果您想要一个可迭代的堆栈,请使用不同的数据结构作为堆栈角色(
std::vector
?)或自己编写一个。