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

问题描述 投票:6回答:6

是否有可能在C ++中遍历std::stack

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

std::stack<int> foo;

// ..

for (__typeof(foo.begin()) it = foo.begin(); it != foo.end();  it++)
{
    // ...
}
c++ stack traversal
6个回答
13
投票

是否可以在C ++中遍历std :: stack?

不是。堆栈是一种数据结构,当您有兴趣将元素放在顶部并从顶部获取元素时,您应该使用它。如果你想要一个可迭代的堆栈,要么为堆栈角色使用不同的数据结构(std::vector?),要么自己编写一个。


2
投票

我认为不可能穿越stack。我能想到的最好的是使用std::vector使用push_back(), pop_back()的矢量

堆栈不提供开始或结束成员函数,因此您不能将它与range based for loop一起使用,这需要两者。

在您的情况下,如果您真的想要迭代它,最好选择一些其他数据结构。


2
投票

正如您所提到的,您需要打印以进行调试,也许这样的事情对您有用:

// 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);
}

正如预期的那样,产出是“9 11”


1
投票

我们无法遍历堆栈。堆栈是一种容器适配器,专门设计用于在LIFO上下文中操作(后进先出),其中元素仅从容器的一端插入和提取。从特定容器的“后面”推送/弹出元素,该容器称为堆栈的顶部。堆栈不是为了显示这种行为,为此我们有其他容器


0
投票
#include <stack>

using std::stack;    

stack< int > numbers;
numbers.push( 1 );
numbers.push( 2 );

while ( not numbers.empty( ) )
{
    int number = numbers.top( );
    numbers.pop( );
}

http://en.cppreference.com/w/cpp/container/stack


-1
投票

你可以做一个for循环:

for (stack<T> newStack = stack; !newStack.empty(); newStack.pop()){
   T item = newStack.top();
}
© www.soinside.com 2019 - 2024. All rights reserved.