How to cross a stack in C ++?

Is it possible to cross std::stackin C ++?

Moving using the following method is not applicable. Because it std::stackdoes not have a member end.

std::stack<int> foo;

// ..

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

Is it possible to traverse std :: stack in C ++?

No. A stack is a data structure that you should use when you are interested in placing items on top and getting items on top. If you need an iterable stack, use either another data structure for the stack role ( std::vector?), Or write it yourself.

+13
source

, stack. , , , std::vector, push_back(), pop_back()

, , .

- , .

+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"

+2

. - , LIFO ( ), . / "" , . , , .

+1
#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

0

for:

for (stack<T> newStack = stack; !newStack.empty(); newStack.pop()){
   T item = newStack.top();
}
-1

Source: https://habr.com/ru/post/1537345/


All Articles