Hello. I've been studying stacks and I just want to know on how to modify this code below, wherein, This program can accept any data types. Can someone help me on how to fix this code below? Any help will do. Thanks.
Since C++17, there are two types std::variant and std::any that can hold values of different types. You can have a std::stack of these types. However these aren't simple types to use.
printStackElements() is very inefficient as it first copies the stack (as the param is passed by value) then it destroys the copied stack as it prints the top element in each loop iteration. Using std::stack, there's not really an efficient way of doing this as you're not provided with a mechanism to access stack elements other than the top one - not even begin() and end()!
However, std::stack is based around another container (dequeue by default) and the various elements of these can be accessed. If a new class is derived from std::stack then you can have function(s) in this derived class that directly access the stack's elements. Consider: