You're right, std::stack
doesn't provide a direct way to iterate over its elements. This is intentional and aligns with the purpose of the stack data structure, which is designed for LIFO (last-in, first-out) access where only the top element is accessible.
However, if you really need to iterate over a stack's elements, you have a couple of options:
You can pop each element off the stack one by one until the stack is empty. However, this will destroy the stack in the process:
#include <iostream>
#include <stack>
int main() {
std::stack<int> s;
s.push(1);
s.push(2);
s.push(3);
while (!s.empty()) {
int top = s.top();
std::cout << top << ' ';
s.pop();
}
}
3 2 1
std::stack
 is a container adaptor, which means it uses another container internally. By default, it uses std::deque
.
If you're okay with depending on implementation details, a method like _Get_container()
in MSVC provides access to the underlying container, which you can then iterate over:
#include <iostream>
#include <stack>
int main() {
std::stack<int> s;
s.push(1);
s.push(2);
s.push(3);
const std::deque<int>& d = s._Get_container();
for (int i : d) {
std::cout << i << ' ';
}
}
1 2 3
However, accessing the underlying container like this is not recommended as it's not part of the public interface of std::stack
. It relies on implementation details that are not part of the C++Â specification.
This means that different compilers may use a different way to provide access to the underlying container, and some may not provide it at all.
If you find yourself frequently needing to iterate over a stack, it might be a sign that a stack is not the right data structure for your use case. Consider if a std::vector
or std::deque
would be more appropriate.
Answers to questions are automatically generated and may not have been reviewed.
std::stack
An introduction to the stack data structure, and the standard library implementation - std::stack