在c++中,我如何打印出堆栈的内容并返回其大小?

std::stack<int>  values;
values.push(1);
values.push(2);
values.push(3);

// How do I print the stack?

最佳答案

您可以复制堆栈并逐一弹出项目以将其转储:

#include <iostream>
#include <stack>
#include <string>

int main(int argc, const char *argv[])
{
    std::stack<int> stack;
    stack.push(1);
    stack.push(3);
    stack.push(7);
    stack.push(19);

    for (std::stack<int> dump = stack; !dump.empty(); dump.pop())
        std::cout << dump.top() << '\n';

    std::cout << "(" << stack.size() << " elements)\n";

    return 0;
}

输出
19
7
3
1
(4 elements)

在此处实时查看:http://liveworkspace.org/code/9489ee305e1f55ca18c0e5b6fa9b546f

10-07 19:12
查看更多