Introduction to Stacks using std::stack

Iterating over a std::stack

How can I iterate over all the elements in a std::stack? There don't seem to be any obvious methods for this.

Illustration representing computer hardware

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:

Pop and process

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

Access the underlying container

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.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved