如何在C++中遍历堆栈?

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?),要么自己编写一个.


Aru*_*yan 8

不可能直接遍历 an,std:: stack因为它没有end成员,这就是堆栈数据结构应该是这样的,即只有一个指针。但是,仍然有两个懒惰的技巧可以遍历它:

1) 基于循环:

while(!st.empty()) {
        cout << s.top();
        s.pop();
    }
Run Code Online (Sandbox Code Playgroud)

基于循环的方法的问题:

  • 原始堆栈变空。

2) 基于递归:

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”

  • 有人否决了这一点,因为堆栈不应该这样使用。但你说这是为了调试目的,你是对的。开发人员必须在生产中采取正确的行为,但为了测试有时有必要打破一些默认行为。 (3认同)