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

30

在C++中,能否遍历std::stack

以下方法不能用于遍历。因为std::stack没有成员end

std::stack<int> foo;

// ..

for (__typeof(foo.begin()) it = foo.begin(); it != foo.end();  it++)
{
    // ...
}

2
这就是为什么它被称为“堆栈”。理论上,后进先出,就是这样。 - deviantfan
2
可能是Does std::stack expose iterators?的重复问题。 - marcinj
4
你选择了错误的数据类型。如果想要迭代它,请不要使用堆栈(stack)。 - David Heffernan
12个回答

0

由于 c++ 的堆栈没有某种类型的迭代器,因此这是带有迭代器的基本堆栈。

MutantStack.hpp

#pragma once

#include <stack>

template <class T>
class MutantStack : public std::stack<T>
{
public:
    typedef typename std::stack<T>::container_type::iterator iterator;
    typedef typename std::stack<T>::container_type::const_iterator const_iterator;

    MutantStack(void) {}

    iterator begin(void)
    {
        return this->c.begin();
    }

    iterator end(void)
    {
        return this->c.end();
    }

    const_iterator cbegin(void) const
    {
        return this->c.cbegin();
    }

    const_iterator cend(void) const
    {
        return this->c.cend();
    }
};

-2
你可以使用for循环:
for (stack<T> newStack = stack; !newStack.empty(); newStack.pop()){
   T item = newStack.top();
}

我在这里看到一个语法错误!此外,OP正在寻找一种不会弹出所有内容的解决方案。 - Ignatius

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接