2

I am trying to workaround with STL stack where in I wish to display stack elements. But I don't find any efficient approach to display without popping each element.

ceasif
  • 345
  • 2
  • 14
  • I don't think this is a duplicate of the question about whether it has iterators. The question is about how to print the stack, not about iterators. – Sebastian Mach Feb 27 '18 at 05:52
  • You can inherit from `std::stack` to provide iteration functionality. See, e.g., https://stackoverflow.com/a/49001896/580083 – Daniel Langr Feb 27 '18 at 07:06

3 Answers3

4

A stack is a container adapter. It's sole purpose is to take some other type of container (a std::deque by default) and restrict the visible interface to that container to the few operations allowed for a stack. Among other things, that means that the only element in a stack that you can observe is the top.

If you need to observe other elements being stored, then you don't want to use a stack. The most obvious choice is to use a std::deque (or std::vector) directly. When you need stack-like access, you can use push_back, back and pop_back to get it. When you need access to internal elements, you can use begin(), end(), operator[], at(), etc., to get that.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

stack is a container adapter and you can't access underlying container in a portable way.

If you really need to iterate through stack, then probably stack is a bad choice for you and you need to find another container which fits your needs,

Yola
  • 18,496
  • 11
  • 65
  • 106
0

If you don't want to break the stack-contract, but want to print out the contents for testing purposes, you can copy the stack into another, throw-away one:

#include <stack>
#include <vector>
#include <iostream>

int main() {
    std::stack<int> foo;
    foo.push(1);
    foo.push(2);
    foo.push(3);

    std::stack<int> bar { foo };

    while(bar.size()) {
        std::cout << " - " << bar.top() << '\n';
        bar.pop();
    }

    std::cout << "foo-size: " << foo.size() << '\n';
    std::cout << "bar-size: " << bar.size() << '\n';
}

Notwithstanding, if you regularly need random- or sequence-access to the stack's elements, you should use a container which allows random- or sequence-access:

Sebastian Mach
  • 38,570
  • 8
  • 95
  • 130
  • std::stack bar { foo }; --> can you give me reference for understanding this – ceasif Feb 27 '18 at 08:56
  • @ceasif: The braces are part of C++11's efforts to unify initialization (more here: https://akrzemi1.wordpress.com/2011/06/29/brace-brace/). The meaning of that line is that `bar` gets copy-initialized with `foo`. One could also write `std::stack bar = foo` or `std::stack bar(foo)` – Sebastian Mach Feb 27 '18 at 13:11