Is it possible to traverse std::stack
in C++?
Traversing using following method is not applicable. Because std::stack
has no member end
.
std::stack<int> foo;
// ..
for (__typeof(foo.begin()) it = foo.begin(); it != foo.end(); it++)
{
// ...
}
Is it possible to traverse std::stack in C++?
No. A stack is a data structure you should use when you are interested in placing elements on top and getting elements from the top. If you want an iterable stack, either use a different data structure for a stack role (std::vector
?) or write one yourself.
I don't think that it is possible to traverse through a stack. The best I can think of is using vector using std::vector
using push_back(), pop_back()
The stack does not provide a begin or end member function so you cannot use it with a range based for loop which requires both.
In your case it would be better to choose some other data structure if you really want to iterate through it.
As you mentioned you need printing for debugging purposes, maybe something like this would work for you:
// 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);
}
Output is, as expected, "9 11"
We can't traverse through stack. Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first-out), where elements are inserted and extracted only from one end of the container. Elements are pushed/popped from the "back" of the specific container, which is known as the top of the stack. It is not intended for stack to show this behavior, for this we have other containers
#include <stack>
using std::stack;
stack< int > numbers;
numbers.push( 1 );
numbers.push( 2 );
while ( not numbers.empty( ) )
{
int number = numbers.top( );
numbers.pop( );
}
You can do a for loop:
for (stack<T> newStack = stack; !newStack.empty(); newStack.pop()){
T item = newStack.top();
}
来源:https://stackoverflow.com/questions/23194548/how-to-traverse-stack-in-c