How to list all the elements in a stack c++?

We can list all the elements from the stack c++ by

we could create a copy of the stack and pop items one by one to out them

 

#include <iostream>
#include <stack>
#include <string>
int main(int argc, const char *argv[])
{
std::stack<int> stack;
stack.push(9);
stack.push(12);
stack.push(16);
stack.push(27);
for (std::stack<int> temp = stack; !temp.empty(); temp.pop())
std::cout << temp.top() << '\n';
std::cout << "(" << stack.size() << " elements)\n";
return 0;
}

 

Output

27                                                                                                                                   
16                                                                                                                                   
12                                                                                                                                   
9                                                                                                                                    
(4 elements)