acc*_*uck 7 c++ stack traversal
是否可以std::stack
在C++中遍历?
使用以下方法遍历不适用.因为std::stack
没有会员end
.
std::stack<int> foo;
// ..
for (__typeof(foo.begin()) it = foo.begin(); it != foo.end(); it++)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
utn*_*tim 14
是否可以在C++中遍历std :: stack?
不是.堆栈是一种数据结构,当您有兴趣将元素放在顶部并从顶部获取元素时,您应该使用它.如果你想要一个可迭代的堆栈,要么为堆栈角色使用不同的数据结构(std::vector
?),要么自己编写一个.
不可能直接遍历 an,std:: stack
因为它没有end
成员,这就是堆栈数据结构应该是这样的,即只有一个指针。但是,仍然有两个懒惰的技巧可以遍历它:
while(!st.empty()) {
cout << s.top();
s.pop();
}
Run Code Online (Sandbox Code Playgroud)
基于循环的方法的问题:
template <typename T>
void traverse_stack(stack<T> & st) {
if(st.empty())
return;
T x = st.top();
cout << x << " ";
st.pop();
traverse_stack(st);
st.push(x);
}
Run Code Online (Sandbox Code Playgroud)
基于递归的方法的优点:
基于递归的方法的问题:
小智 5
正如您提到的,您需要打印以进行调试,也许这样的东西适合您:
// Example program
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <algorithm>
template <typename T>
void StackDebug(std::stack<T> s)
{
std::vector<T> debugVector = std::vector<T>();
while (!s.empty( ) )
{
T t = s.top( );
debugVector.push_back(t);
s.pop( );
}
// stack, read from top down, is reversed relative to its creation (from bot to top)
std::reverse(debugVector.begin(), debugVector.end());
for(const auto& it : debugVector)
{
std::cout << it << " ";
}
}
int main()
{
std::stack< int > numbers;
numbers.push( 9 );
numbers.push( 11 );
StackDebug(numbers);
}
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,输出为“9 11”