如何在不弹出元素且不循环的情况下在 C++ 中打印整个堆栈?

How to print whole stack in C++ in without popping out elements and without loop?

在Java中我们可以像

那样打印一个堆栈
Stack<Integer> s = new Stack<>();
System.out.print(s);

如何在 C++ 中做同样的事情,而不弹出元素和循环?

std::stack 没有任何 public 函数可以让你迭代它。但是 std::stack 使用 std::deque 作为它的数据结构:

它是 protected 成员,因此您可以继承 std::stack 并授予对其底层数据结构的访问权限,而无需复制它。 System.out.print(s); 最终使用循环遍历 s 项并打印它。您可以通过重载 operator<<(std::ostream&, T const&):

在 C++ 中完成此操作
template<typename T>
struct my_stack final : std::stack<T>
{
    auto begin() const
    {
        return std::stack<T>::c.cbegin();
    }
    auto end() const
    {
        return std::stack<T>::c.cend();
    }

    friend std::ostream& operator<<(std::ostream& out, my_stack const& in)
    {
        std::for_each(in.begin(), in.end(), [&out](auto const &i)
        {
            out << i << '\t';
        });
        return out;
    }
};

int main()
{
    my_stack<std::string> stack;
    stack.push("1");
    stack.push("2");
    stack.push("3");
    stack.push("4");

    std::cout << stack << std::endl;
}